42

我正在阅读Wikipedia 上关于C++11 Type Inference feature的这篇文章。

有一个例子,我引用:

#include <vector>
int main() {  
    const std::vector<int> v(1);  
    auto a = v[0];        // a has type int  
    decltype(v[1]) b = 1; // b has type const int&, the return type of  
                          //   std::vector<int>::operator[](size_type) const  
    auto c = 0;           // c has type int  
    auto d = c;           // d has type int  
    decltype(c) e;        // e has type int, the type of the entity named by c  
    decltype((c)) f = c;  // f has type int&, because (c) is an lvalue  
    decltype(0) g;        // g has type int, because 0 is an rvalue  
}

在以下几行中:

    decltype(c) e;        // e has type int, the type of the entity named by c  
    decltype((c)) f = c;  // f has type int&, because (c) is an lvalue  

c和有什么区别(c)?为什么(c)表示左值

4

2 回答 2

23
  • c是变量的名称;

  • (c)是一个表达式,在这种情况下是一个左值表达式,其值与变量的值相同c

并且两者区别对待decltype。例如,考虑 ,decltype(1+2)这也是采用表达式的示例。碰巧您的示例是一个简单版本的表达式:它仅命名一个变量并且没有任何令人兴奋的内容。

如果您对语言规范的细微部分进行合理化,那么您通常只会真正关心这些差异之一。但是,正如您所指出的,它在这种情况下具有相当重要的实际效果。

请注意,这里没有使用运算符。这一切都只是对语法布局的推论。

于 2013-01-02T00:57:16.253 回答
11

我在这里找到了一个很好的描述。它描述了以下之间的区别:

struct A { double x; };
const A* a = new A();
...
decltype(a->x) x4; // type is double
decltype((a->x)) x5; // type is const double&

我引用:

后两种 decltype 调用之间存在差异的原因是括号中的表达式(a->x)既不是 id 表达式也不是成员访问表达式,因此不表示命名对象。[ 13 ]

因为表达式是一个左值,所以它的推导类型是“对表达式类型的引用”,或者const double&。[ 10 ]

于 2013-01-02T23:06:26.247 回答