search

Home  >  Q&A  >  body text

C++ decltype((i))为什么是个引用?

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一个引用。

求解释,万分感谢!

阿神阿神2804 days ago591

reply all(3)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 11:27:03

    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.

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 11:27:03

    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

    reply
    0
  • 黄舟

    黄舟2017-04-17 11:27:03

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

    reply
    0
  • Cancelreply