c++ - C++ 中 (x) 的类型

标签 c++ language-lawyer c++14 decltype

给定:

decltype(auto) f1()
{
    int x = 0;
    return x;  // decltype(x) is int, so f1 returns int
}
decltype(auto) f2()
{
    int x = 0;
    return (x);  // decltype((x)) is int&, so f2 returns int&
}

(取自 Scott Meyer 的 Effective Modern C++)。

现在,如果我找到了正确的段落,C++ 标准的第 7.1.5.2 节简单类型说明符 [dcl.type.simple] 说:

If e is an id-expression or a class member access (5.2.5 [expr.ref]), decltype(e) is defined as the type of the entity named by e

该部分的示例是:

struct A { double x; }

const A* a = new A();

decltype((a->x)); // type is const double&

现在,我想知道为什么decltype((x))在书中被推导出为int&

最佳答案

相关标准引用为:

N4140 [dcl.type.simple]/4: For an expression e, 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.

由于x是左值,并且表达式是带括号的,所以使用第三条规则,所以decltype((x))int&.

关于c++ - C++ 中 (x) 的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33479631/

相关文章:

c++ - 有没有办法使用 move 而不是复制语义来包装Python中的函数返回值(对象)?

c++ - 限制枚举类的位数

c++ - Windows 应用程序需要焦点

c++ - 模板参数中的相同长度相同符号整数类型

c++ - 枚举位域和聚合初始化

c++ - 为什么允许将派生类的方法静态转换为基类的方法?

c++ - 有条件的 constexpr 成员函数

c++ - [C++14]我正在使用 pair 但没有输出

c++ - 开始使用适用于 Windows 的 ISOCPP.net C++ 构建时遇到问题 (nuwen)

c++ - 在其函数定义中使用相同的函数?