C++11为什么 'decltype(x)'和 'decltype((x))'的类型不同?

标签 c++11 variables types expression decltype

我发现它们是不同的,并且语言标准规定了每个语句应该检索什么样的类型(变量和表达式之间的差异)。但我真的很想知道为什么这两种类型应该不同?

#include<stdio.h>
int x=0;
decltype((x)) y=x;
int main()
{
    y=2;
    printf("%d,",x);
    decltype((1+2))&z=x;//OK (1+2) is an express, but why decltype should differ?
    z=3;
    printf("%d\n",x);
    return 0;
}

运行结果为'2,3'

那么为什么decltype((int))的设计是int&,这里C++语言设计是出于什么考虑呢?任何语法一致性都需要这样的设计吗? (我不希望得到“这是设计使然”)

感谢您的解释。

最佳答案

如果您读过例如this decltype reference你会看到

2) If the argument is an unparenthesized id-expression or an unparenthesized class member access expression, ...

3) If the argument is any other expression...

... b) if the value category of expression is lvalue, then decltype yields T&;

[强调我的]

然后再往下一点

Note that if the name of an object is parenthesized, it is treated as an ordinary lvalue expression, thus decltype(x) and decltype((x)) are often different types.

因为您使用括号表达式,所以它被视为左值,这意味着上面的 3.b 处于事件状态,并且 decltype((x)) 为您提供 int& if xint

应该注意的是,虽然该引用文献不具有权威性,但它源自规范,并且通常可靠且正确。

<小时/>

摘自 C++11 规范 ISO/IEC 14882:2011,第 7.1.6.2 节 [dcl.type.simple],第 4 小节:

The type denoted by decltype(e) is defined as follows:

— if e is an unparenthesized id-expression or an unparenthesized class member access (5.2.5), decltype(e) is the type of the entity named by e. If there is no such entity, or if e names a set of overloaded functions, the program is ill-formed;

— otherwise, if e is an xvalue, decltype(e) is T&&, where T is the type of e;

— otherwise, if e is an lvalue, decltype(e) is T&, where T is the type of e;

— otherwise, decltype(e) is the type of e

举个例子:

struct A { double x; };
const A* a = new A();
...
decltype((a->x)) x4 = x3; // type is const double&

基本上与之前链接的引用文献所说的完全一样。

在您的示例中,规范中的 e(x) (因为您有 declspec((x)))。现在第一种情况不适合,因为 (x) 不是不带括号的表达式。第二种情况不适合,因为 (x) 不是 xvalue 。第三种情况匹配,(x)int 类型的左值,导致 decltype((x))int& .

所以您的问题的答案很简单:因为规范是这么说的。

关于C++11为什么 'decltype(x)'和 'decltype((x))'的类型不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42363040/

相关文章:

Python len() 不返回整数

c++ - 在 C/C++ 中创建 10 位数据类型

c++ - 在 std::cout 刷新事件上捕获和引发事件

jquery - 将变量传递给 .animate() 函数 JQuery

c++ - c++ using 指令的范围

swift - let 和 var Swift REPL 中 const 的重新声明无效

python - python初学者错误中的变量增量

c# - 在 C# 中,Type.FullName 何时返回 null?

c++ - 使用 vector<char> 作为缓冲区而不在 resize() 上初始化它

c++ - 如何检查所有可变参数模板参数是否具有特殊功能?