gpt4 book ai didi

c++ - 关于 const decltype(x)& 的问题

转载 作者:可可西里 更新时间:2023-11-01 16:42:20 25 4
gpt4 key购买 nike

考虑以下代码:

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

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

错误:“const”限定符不能应用于“const int&”

根据标准,哪个是正确的?我的猜测是 GCC 符合标准,就像您不能执行 int& const b = a; 一样。

最佳答案

我相信代码是有效的并且两种类型是相同的。

[dcl.ref]/1 说:

Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef-name (7.1.3, 14.1) or decltype-specifier (7.1.6.2), in which case the cv-qualifiers are ignored.

由于您是通过decltype-specifier 引入第一个const,它会被忽略,您的第一个类型等同于decltype(b)&.

现在 [dcl.ref]/6 说:

If a typedef-name (7.1.3, 14.1) or a decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a type T, an attempt to create the type "lvalue reference to cv TR" creates the type "lvalue reference to T" [...]

您的 decltype-specifier 表示类型“对 const int 的引用”,并且您正试图创建一个左值引用,因此您最终得到一个左值引用const int.

关于c++ - 关于 const decltype(x)& 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29540907/

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