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

Nee*_*asu 4 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;
}
Run Code Online (Sandbox Code Playgroud)

上面的代码没有编译

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’
Run Code Online (Sandbox Code Playgroud)

但是如果我更换const_reference_type data() constconst value_type& data() const它的工作原理.如果我typedef const reference_type const_reference_type
typedef const value_type& const_reference_type它替换编译

Jos*_*eld 6

你的const_reference_typetypedef不符合你的想法:

typedef const reference_type const_reference_type;
Run Code Online (Sandbox Code Playgroud)

const_reference_typeint& const- 也就是说,整个类型reference_type已经const应用于它 - 并且const引用不能存在,所以你得到了int&.你没有const int&达到预期的效果.

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

typedef const value_type& const_reference_type;
Run Code Online (Sandbox Code Playgroud)

这里的提示是不要只考虑typedef类型名称的查找和替换,因为它不会那样.

  • 这就是为什么我更喜欢在右侧而不是左侧应用"const".它使模板代码和typedef易于阅读. (2认同)