为什么 decltype(a, b) 被评估为引用?

Why decltype(a, b) is evaluated to a reference?

根据这个 answerref 应该是 int

但出于某种原因,它在 gcc 和 MSVC2015 中的计算结果为 int&,而 decltype(b) 仅正确计算为 int。为什么会这样?

int a = 1, b = 2;
decltype(a, b) ref; // ref is int&
decltype(b) var;    // var is int

a, b 是一个表达式。根据表达式的 decltype 规则,如果表达式的结果是左值,类型将被推断为 T&

7.1.6.2/4 Simple type specifiers [dcl.type.simple]
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.

关于 "type of the entity named by e""type of e" 之间的区别的混淆部分很容易通过示例理解:

如果某个实体e声明为int& e = x;,那么稍后,在表达式e中,类型einte命名实体的类型是int&。简而言之,type of e 删除引用限定符。

出于与 decltype((a)) refref 声明为参考(int &,而不是 int)相同的原因。

decltype 规则在处理表达式而不是实体时是不同的。 a, b 表达式的值类别是左值,因此 decltype(a, b) 产生 T& -> int &

另见 http://en.cppreference.com/w/cpp/language/decltype