#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() const与const value_type& data() const它的工作原理.如果我typedef const reference_type const_reference_type
用typedef const value_type& const_reference_type它替换编译
你的const_reference_typetypedef不符合你的想法:
typedef const reference_type const_reference_type;
Run Code Online (Sandbox Code Playgroud)
const_reference_type是int& const- 也就是说,整个类型reference_type已经const应用于它 - 并且const引用不能存在,所以你得到了int&.你没有const int&达到预期的效果.
正如您所指出的,此处的修复方法是:
typedef const value_type& const_reference_type;
Run Code Online (Sandbox Code Playgroud)
这里的提示是不要只考虑typedef类型名称的查找和替换,因为它不会那样.