关于C ++ 0x参考崩溃的问题 [英] Question about C++0x reference collapse
问题描述
我不知道为什么这些代码不能编译。我在Visual c + + 2010和gcc测试与-std = c + + 0x。任何人给一些建议?
谢谢!
I don't know why these code can't be compiled. I'v tested in Visual c++ 2010 and gcc with -std=c++0x. anyone give some suggestion? thanks!
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)':成员函数已定义或已声明
compile error: 'void Foo::test(T)' : member function already defined or declared
但为什么可以编译?
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);
}
i'v read c ++ 0x article说: & == T& ,因此const T& & == const T&
i'v read c++0x article said: T& & ==T& , so const T& & == const T& ?
推荐答案
我读了c ++ 0x文章说: & == T& ,因此const T& & == const T& ?
i'v read c++0x article said: T& & ==T& , so const T& & == const T& ?
实际上,这没有什么意义。 IMHO,最好把它放在表格中:
Actually, that doesn't make a lot of sense. IMHO, it's better to put this into a table:
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已经是引用(第二行) const T
适用于参考,而不适用于裁判。但是引用本质上是不变的,因为你不能在初始化后引用另一个对象,所以在这里忽略了一个 const
。你可以认为它是const崩溃。 ; - )
If T is already a reference (2nd row) the const in const T
applies to the reference and not to the referee. But a reference is inherently constant in the sense that you cannot make it refer to another object after initialization, so a const
is just ignored here. You can think of it as "const collapsing". ;-)
这篇关于关于C ++ 0x参考崩溃的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!