【问题标题】:'const decltype((a))' does not declare a const reference?'const decltype((a))' 没有声明 const 引用?
【发布时间】:2015-06-16 14:59:52
【问题描述】:

今天看到一段代码是这样的:

int a = 0;
const decltype((a)) x = 10; // Error

const int b = 0;
decltype ((b)) y = 42; // Correct

我可以看到为什么正确的代码是正确的,但我看不出为什么错误的代码是不正确的。

我测试了一下,发现有点奇怪。

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 引用吗?不,我发现它是一个非常量引用。我可以通过x修改a的值。

为什么const修饰符没有生效?

【问题讨论】:

  • const 应用于引用(并被忽略),而不是引用的类型。
  • decltype 与修饰符组合起来的工作方式与将修饰符应用于typedef-ed 类型完全相同。这不是文本替换。
  • @T.C. @ben-voigt 哦,我明白了。所以const 应用到int& 的整个body 上就是const reference to int,而不是仅仅结合它就是const int&,引用const int...对吧?
  • intint& 类型中更“内部”的类型,而 const 坚持作为参考的外部类型。只需在右侧添加 const 并读取结果类型:“const reference to int”
  • @ixSci 谢谢,我完全理解你的意思。但是我很好奇为什么你们都在评论而不是回答?

标签: c++ c++11 decltype


【解决方案1】:

不正确的部分是不正确的,因为const 应用于完整类型,即int&,并将const 添加到int& 使其成为int& const,即对int 的const 引用。但是引用的本质是const,所以 const 部分被忽略了。因此结果类型仍然是int&

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    • 2014-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    相关资源
    最近更新 更多