C++ decltype((i))为什么是个引用?
阿神
阿神 2017-04-17 11:25:03
0
3
590
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一个引用。

求解释,万分感谢!

阿神
阿神

闭关修行中......

reply all(3)
左手右手慢动作

First erase the outermost decltype():

  • decltype((i)) -> (i)
  • decltype(i) -> i

In other words, the first decltype corresponds to (i), and the second one handles i.

In C++ expressions, the first one is "lvalue expression"; the second one is "a variable".
Because it is lvalue, decltype will be understood as a reference.

刘奇

There is this sentence earlier in the book:

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

So decltype when applied to an lvalue will return a reference type

黄舟

Because the type of (i) is a reference.
decltype(var) is the type of this variable; decltype(expr) is the type of this expression.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template