gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:51:10 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com