【问题标题】:Do decltype(c) e; and decltype((c)) f; declare different types? [duplicate]做 decltype(c) e;和 decltype((c)) f;声明不同的类型? [复制]
【发布时间】:2012-10-02 12:04:14
【问题描述】:

可能重复:
decltype and parenthesis

我在维基百科上找到了这个:

    auto c = 0;           // c has type int
    auto d = c;           // d has type int
    decltype(c) e;        // e has type int, the type of the entity named by c
    decltype((c)) f = c;  // f has type int&, because (c) is an lvalue

使用 ideone 编译器(C++0x idk 他们使用什么)和 typeinfo 我无法看到 e 和 f 之间的差异。显然,我可能失败了,所以我想知道这是否是最终的 C++11 标准行为。

【问题讨论】:

    标签: c++ c++11 decltype


    【解决方案1】:

    是的,这是标准行为。它写在 §7.1.6.2[dcl.type.simple]/4 中,其中:

    decltype(e)表示的类型定义如下:

    • 如果e未加括号的id-expression 或未加括号的类成员访问,decltype(e) 是由 e 命名的实体的类型。
    • ...
    • 否则,如果e是左值,decltype(e)就是T&,其中Te的类型;
    • ...

    由于c 没有括号并且是一个id 表达式(这里是一个标识符,参见§5.1.1[expr.prim.general]/7),decltype(c) 将是c 的类型,即int

    由于(c) 确实有括号并且是一个左值(例如(c)=1 是一个有效的表达式),所以decltype((c)) 将是(c) 类型的左值引用类型,即int&

    【讨论】:

    • 很高兴知道,顺便说一句,C++ 的任何其他部分 (SOMETHING) 具有一个语义和 ((SOMETHING)) 差异语义。
    • @NoSenseEtAl: 1-2*3 vs (1-2)*3, int*x[10] vs int(*x)[10], ... ?
    • 你没听懂我的意思.... (1-2)*3 和 ((1-2))*3 一样
    • @NoSenseEtAl:宏的。 FOO(x,y)传递两个参数x和y,FOO((X,Y))传递一个参数(X,Y)
    • @NoSenseEtAl 题外话,但无论如何,当x 是一个整数时,int f(int(x)); 声明一个函数f(int),而int f((int(x))); 声明一个整数f=x (most vexing parse)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    相关资源
    最近更新 更多