Search code examples
c++language-lawyerc++17value-categories

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


Say we have the following declaration:

struct S {
  int a;
};

What is the type denoted by the following simple-type-specifier? Is it int or int&&?

decltype(S{}.a)

(This question is intended to address C++17, but answers addressing other versions of the standard are also appreciated.)


Solution

  • It's int. Per [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;

    • [...]

    The entity named by S{}.a is a, which is of type int. Therefore, decltype(S{}.a) denotes the type int. (Thanks to comment for pointing this out!)


    As mentioned in a comment, although the type denoted by decltype(S{}.a) is int, S{}.a is an xvalue and can be bound to int&& as in:

    int&& rv = S{}.a;