我不知道为什么这些代码无法编译。我已经在 Visual c++ 2010 和 gcc 中使用 -std=c++0x 进行了测试。有人给点建议吗? 谢谢!
template<typename T>
class Foo
{
public:
void test(const T&){cout<<"const";}
void test( T&){cout<<"non const";}
};
int main()
{
int a;
Foo<int&> f;
}
编译错误:'void Foo::test(T)': 成员函数已经定义或声明
但是为什么这个可以编译呢?
template<typename T> void foo(const T&){cout<<"const"; }
template<typename T> void foo( T&){cout<<"non const"; }
int main()
{
int a;
foo<int&>(a);
}
我读过 c++0x 文章说: T& & ==T& ,所以 const T& & == const T& ?
最佳答案
i'v read c++0x article said: T& & ==T& , so const T& & == const T& ?
实际上,这并没有多大意义。恕我直言,最好将其放入表格中:
T T& const T const T&
---------------------------------------
int int& const int const int&
int& int& int& int&
(1) (2) (1+2)
1: Reference collapsing in action
2: const applies to the reference and is therefore ignored
如果 T 已经是引用(第 2 行),则 const T
中的 const 适用于 reference 而不是 referee。但是引用本质上是常量,因为你不能在初始化后让它引用另一个对象,所以 const
这里被忽略了。您可以将其视为“const 崩溃”。 ;-)
关于c++ - 关于C++0x引用崩溃的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4425182/