int i = 42;
decltype((i)) d; //error: d is int& and must be initialized
decltype(i) e; //ok: e is an (uninitialized) int
下面是引自 《C++ primer 5th edition》的一段话:在2.5 Dealing with types的“decltype and reference” 这一小节里面
If we wrap the variable’s name in one or more sets of parentheses, the compiler will evaluate the operand as an expression. A variable is an expression that can be the left-hand side of an assignment. As a result, decltype on such an expression yields a reference
不能理解为什么 left-hand side of an assignment 会使得decltype最后yield一个引用。
求解释,万分感谢!
ringa_lee2017-04-17 11:27:03
首先把最外面的 decltype() 给抹掉:
decltype((i))
-> (i)
decltype(i)
-> i
也就是说,第一个decltype
是对应(i)
,第二个处理i
。
在C++表达式中,第一个是"lvalue表达式";第二个是"一个变量"。
因为是lvalue
,因此decltype
会理解为引用。
怪我咯2017-04-17 11:27:03
书中稍早一点有这样一句话:
As we’ll see in § 4.1.1 (p. 135), some expressions will cause decltype to yield a reference type. Generally speaking, decltype returns a reference type for expressions that yield objects that can stand on the left-hand side of the assignment
所以decltype作用在左值上会返回引用类型