Cyb*_*Luc 6 c++ decltype c++11
今天我看到了一些这样的代码:
int a = 0;
const decltype((a)) x = 10; // Error
const int b = 0;
decltype ((b)) y = 42; // Correct
Run Code Online (Sandbox Code Playgroud)
我可以看到为什么正确的代码是正确的,但我不明白为什么错误的代码不正确.
我测试了它,发现它有点奇怪.
const decltype((a)) x = 10;
这应该是一个const int&
权利?但它不编译!error: non-const lvalue reference to type 'int' cannot bind to a temporary of type 'int'
.
我把它改成了const decltype((a)) x = a;
然后编译.
那么,是x
一个const参考?不,我发现它是一个非const引用.我可以修改它a
的价值x
.
为什么const
修饰符不起作用?
因为不正确的部分是不正确const
施加到完整的类型是int&
,加入const
到int&
使得int& const
其是const引用为int.但是引用const
本质上是因为const部分被忽略了.因此,结果类型仍然是int&