C++ decltype((i))为什么是个引用?
阿神
阿神 2017-04-17 11:25:03
0
3
493
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)
左手右手慢动作

首先把最外面的 decltype() 给抹掉:

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

也就是说,第一个decltype是对应(i),第二个处理i

在C++表达式中,第一个是"lvalue表达式";第二个是"一个变量"。
因为是lvalue,因此decltype会理解为引用。

    刘奇

    书中稍早一点有这样一句话:

    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作用在左值上会返回引用类型

      黄舟

      因为(i)的类型就是个引用啊。
      decltype(var)就是这个变量的类型;decltype(expr)就是这个表达式的类型。

        Latest Downloads
        More>
        Web Effects
        Website Source Code
        Website Materials
        Front End Template
        About us Disclaimer Sitemap
        php.cn:Public welfare online PHP training,Help PHP learners grow quickly!