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一个引用。
求解释,万分感谢!
First erase the outermost decltype():
decltype((i))
->(i)
decltype(i)
->i
In other words, the first
decltype
corresponds to(i)
, and the second one handlesi
.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:
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.