#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
编译