模板中的“const const T”

时间:2011-10-13 11:38:32

标签: c++ templates const

以下代码编译并适用于G ++ 4.4.0和MS VC2008 Express。

#include <iostream>

template<typename T> struct A{
protected:
    T v;
public:
    const T get() const{
        return v;
    }

    A(T v_)
    :v(v_){
    }
};

class B: public A<const int*>{
public:
    void doSomething() const{
        const int* tmp = get();
        std::cout << *tmp << std::endl;
    }

    B(const int* p)
    :A<const int*>(p){
    }
};

int main(int argc, char** argv){
    int a = 134;
    B b(&a);
    const B& c = b;
    b.doSomething();
    c.doSomething();
    return 0;
}

但是,据我所知,使用A<const int*>会导致const const int* A::get() const;。而且我很确定我在实际代码中没有看到类似的东西。以这种方式使用模板“合法”吗?

如果没有,有什么替代方案?在我的代码中,我需要一个模板类,它提供两个“getter”方法(const / non-const),并且可以将“const int *”作为一个类型。像这样:

template<typename T> struct A{
protected:
    T v;
public:
    const T get() const{
        return v;
    }

    T get(){
        return v;
    }

    A(T v_)
    :v(v_){
    }
};

有什么想法吗?

6 个答案:

答案 0 :(得分:5)

如果T = const int *,则const Tconst int * const

答案 1 :(得分:4)

拥有多个const限定符不是问题:它们只是折叠在一起。

但是你误解了它,因为你没有正确地放置它(语法允许它是一种耻辱)。

如果您将<{1}} 放在之后的类型,那么您就会发现自己读错了。

const const T T const int*不是const const int* = const int*

如果你写得正确:T const其中Tint const*,那么你会读到它int const* const,它是指向{的const指针{1}} int,而不是指向const int。

的指针

答案 2 :(得分:3)

我们可以翻译

const int *

int const *

指向常量int的指针。 当你有T = int *时,const T的含义是:

int * const

这意味着,一个指向int的常量指针。

所以在T = const int *的情况下,这是 int const * ,你对const T的看法是:

int const * const

这意味着指向常量int的常量指针。这是合法的。

如果不是所需的行为,您可能会有部分专业化,例如:

template<typename T> struct A<const T>{
//here comes different implementation for the case where A template is
//initialized with a const type.

答案 3 :(得分:2)

It's fine要做到这一点

struct Foo {};
typedef const Foo CFoo;

const CFoo c;

答案 4 :(得分:1)

所有其他答案都代表constness,如果你想要不合格的类型,你可以使用一个小模板头骨 - duggery ..

template <typename T>
struct remove_const
{
  typedef T type;
};

template <typename T>
struct remove_const<T*>
{
  typedef T* type;
};

template <typename T>
struct remove_const<const T>
{
  typedef T type;
};

template <typename T>
struct remove_const<const T*>
{
  typedef T* type;
};

template <typename T>
void foo (T& b)
{
  typename remove_const<T>::type a = b;
}

如果您将const指针传递给foo,您会看到a具有非const类型,因此分配失败。

答案 5 :(得分:0)

const int const *是合法代码,表示指向常量值的常量指针。您的代码可能会转换为相同的表达式。

相关问题