#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;
}
上面的代码无法编译const_reference_type没有编制,但常量VALUE_TYPE和编译
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 value_type& data() const
取代const_reference_type data() const
它的工作原理。另外,如果我与typedef const value_type& const_reference_type
替换typedef const reference_type const_reference_type
它编译
'typedef'中的'const'不会做你认为它的作用。 –
[在C++中使用typedef和模板的常量引用]的可能重复(http://stackoverflow.com/questions/3801982/constant-references-with-typedef-and-templates-in-c) – Mat
它可以是一个“const (value_type&)'不同于'(const value_type)'(为了澄清而插入大括号)? –