其表达式是 class 类型的临时对象的成员的 decltype 说明符表示的类型是什么?

What is the type denoted by a decltype-specifier whose expression is a member of a temporary object of class-type?

假设我们有以下声明:

struct S {
  int a;
};

以下简单类型说明符表示的类型是什么? 是 int 还是 int&&

decltype(S{}.a)

(此问题旨在解决 C++17, 但也感谢针对其他版本标准的回答。)

int。 每 [dcl.type.simple]/4:

For an expression e, the type denoted by decltype(e) is defined as follows:

  • [...]

  • otherwise, if e is an unparenthesized id-expression or an unparenthesized class member access, 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;

  • [...]

S{}.a命名的实体为a,类型为int。 因此,decltype(S{}.a)表示类型int。 (感谢 指出这一点!)


中所述,虽然decltype(S{}.a)表示的类型是int,但S{}.a是一个xvalue,可以绑定到int&&如:

int&& rv = S{}.a;