给定:
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 expressione
, the type denoted bydecltype(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 bye
. 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)
isT&&
, whereT
is the type of e;- otherwise, if
e
is an lvalue,decltype(e)
isT&
, whereT
is the type of e;- otherwise,
decltype(e)
is the type ofe
.
由于x
是左值,并且表达式是带括号的,所以使用第三条规则,所以decltype((x))
是int&
.
关于c++ - C++ 中 (x) 的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33479631/