c++ - 关于C++0x引用崩溃的问题

标签 c++ c++11

我不知道为什么这些代码无法编译。我已经在 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/

相关文章:

c++ - 使用指针打印函数地址

c++ - x86_64-pc-cygwin-gcc 链接器错误

c++ - Cuda 内存传输开销

c++ - 如何将字符数组转换为字节数组?

c++ - 根据 C++ 中另一个数组的成员对数组进行排序

c++ - SSE 和 iostream : wrong output for floating point types

c++ - 在 for 循环中使用 lambda 函数连接信号槽

c++ - 请解释为什么这个简单的 C++(Qt) 代码工作起来如此奇怪

c++ - 仅当参数可取消引用到某种类型时如何启用函数?

c++ - 使用 CRTP 时 clang++ 不接受使用模板模板参数