decltype((c)) 中括号的意义? [重复]

问题描述 投票:0回答:2

我正在阅读 维基百科上关于

C++11
类型推断 功能的文章。

有一个例子,我引用一下:

#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)
代表 左值

c++ c++11 decltype
2个回答
28
投票
  • c
    是变量的名称;

  • (c)
    是一个表达式,在本例中是一个 lvalue 表达式,其值与变量
    c
    的值相同。

并且两者被

decltype
区别对待。例如,考虑
decltype(1+2)
,这也是采用 表达式 的示例。碰巧您的示例是表达式的“简单”版本:仅命名单个变量,并且没有任何令人兴奋的事情。 这是您通常只有在合理化语言规范的微妙部分时才真正关心的差异之一;不过,正如您所指出的,它在这种情况下具有相当显着的实际效果。

请注意,这里没有

operator

用法。这一切都只是从语法布局中的推论。


12
投票
这里

。它描述了以下之间的区别: 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
]

© www.soinside.com 2019 - 2024. All rights reserved.