const_reference_type没有编译但是const value_type&编译

时间:2013-01-20 19:07:32

标签: c++ gcc const

#include <iostream>

template <typename T>
struct ref_exp{
    typedef T value_type;
    typedef value_type& reference_type;
    typedef const reference_type const_reference_type;

    ref_exp(value_type data): _data(data){}
    const_reference_type data() const {return _data;}
  private:
    value_type _data;
};

int main(){
    ref_exp<int> exp1(2);
    std::cout << exp1.data() << std::endl;

    return 0;
}

以上代码无法编译

ref.cpp: In member function ‘T& ref_exp<T>::data() const [with T = int]’:
ref.cpp:17:   instantiated from here
ref.cpp:10: error: invalid initialization of reference of type ‘int&’ from expression of type ‘const int’

但如果我将const_reference_type data() const替换为const value_type& data() const则可行。如果我替换typedef const reference_type const_reference_type
typedef const value_type& const_reference_type编译

3 个答案:

答案 0 :(得分:6)

您的const_reference_type typedef没有按照您的想法行事:

typedef const reference_type const_reference_type;

const_reference_typeint& const - 即整个类型reference_type已应用const - 并且const引用不可存在,因此您获得int&。你没有得到预期的const int&

正如您所指出的,此处的修复方法是:

typedef const value_type& const_reference_type;

这里的提示是不要将typedef视为类型名称的查找和替换,因为它不会那样。

答案 1 :(得分:4)

const reference_type表示引用是const,而不是引用的对象是const。

typedef int &int_ref;  // int_ref is a reference to a non-const int
typedef const int_ref int_ref_const; 
     // int_ref_const is a const reference to a non-const int

第二种情况下的const限定符基本上是无操作,因为引用是隐式的const。

考虑使用指针的类似案例:

typedef int *int_ptr; // int_ptr is a pointer to a non-const int
typedef const int_ptr int_ptr_const; 
    // int_ptr_const is a const pointer to a non-const int.

答案 2 :(得分:4)

在您的typedef中,const reference_type 等于const value_type &,您似乎在想。相当value_type & const,它实际上是value_type &

这是我更喜欢在右侧而不是在左侧应用const的一个原因。如果你写

reference_type const

然后很明显它实际这个:

value_type & const   //actually

而不是而不是:

value_type const &   //intended
现在很清楚,不是吗?

请注意value_type const &const value_type & 相同的类型。

无论如何,要解决问题,您需要将typedef定义为:

typedef value_type const & const_reference_type;

我更喜欢在右侧申请const

相关问题