【问题标题】:Issues concerning const decltype(x)&关于 const decltype(x)& 的问题
【发布时间】:2015-04-09 14:10:00
【问题描述】:

考虑以下代码:

int a = 1;
const int& b = a;
std::cout << std::is_same<const decltype(b)&, const int&>();

它在 clang 3.5 上编译,而 GCC 4.9 给出以下错误:

error: 'const' qualifiers cannot be applied to 'const int&amp;'

根据标准,哪一个是正确的?我的猜测是 GCC 是符合标准的,就像你做不到 int&amp; const b = a;

【问题讨论】:

  • 哪一行会出错? const int&amp; b = a; 还是下一个?
  • FWIW,对于声明中的 decltype-specifier,引用上的 cv 限定符将被忽略(参见 [dcl.ref])。
  • const decltype(b)&amp;decltype(b)&amp; const 不同,所以我认为您与 int&amp; const 的类比并不是特别合理。
  • @Aracthor:为什么会是const int&amp; b = a 行?
  • @Lightning Racis in Obrit:因为错误只是说“const int&”的“const”有问题,并且“const int& b = a”上有一个“const in&” " 行。

标签: c++ templates metaprogramming language-lawyer decltype


【解决方案1】:

我相信代码是有效的,两种类型是一样的。

[dcl.ref]/1 说:

Cv 限定引用格式错误,除非通过使用 typedef-name (7.1.3, 14.1) 或 decltype-specifier 引入 cv 限定符em> (7.1.6.2),在这种情况下忽略 cv 限定符。

由于您是通过 decltype-specifier 引入第一个 const,因此它被忽略,您的第一个类型等效于 decltype(b)&amp;

现在 [dcl.ref]/6 说:

如果 typedef-name (7.1.3, 14.1) 或 decltype-specifier (7.1.6.2) 表示类型 TR 是对一个类型T,尝试创建类型“对cvTR的左值引用”创建类型“对T的左值引用”[...]

您的 decltype-specifier 表示类型“对const int 的引用”,并且您正在尝试创建左值引用,因此您最终得到了对const int 的左值引用。

【讨论】:

  • 这些不只适用于声明,不适用于模板参数吗?不过,我不明白为什么规则会改变。
  • 所以,一个右值引用类型TR可以被覆盖,获得一个左值引用。
  • @chris 我认为模板的情况受专用于它们的其他规则的约束。
  • @Lingxi,您可以查看reference collapsing 了解这些规则。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-08
  • 1970-01-01
  • 2020-04-02
  • 1970-01-01
  • 2013-09-03
  • 2011-04-17
相关资源
最近更新 更多