【问题标题】:Significance of parentheses in decltype((c))?decltype((c))中括号的意义?
【发布时间】:2012-12-16 10:45:02
【问题描述】:

我正在阅读this article on Wikipedia regarding 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) 代表一个左值

【问题讨论】:

  • 那不是运算符...
  • 如果将int 更改为int&amp;,那就是运算符。
  • @MBZ:这并不能使它成为任何“操作员”。

标签: c++ c++11 decltype


【解决方案1】:
  • c是变量名;

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

decltype 对两者的处理方式不同。例如,考虑decltype(1+2),这也是一个采用表达式的例子。碰巧你的例子是一个表达式的 simple 版本:它只是命名一个变量,并没有用它做任何令人兴奋的事情。

这是您通常只有在合理化语言规范的微妙部分时才真正关心的差异之一;但是,正如您所指出的,它在这种情况下具有相当显着的实际效果。

请注意,这里没有 operator 用法。这一切都只是从语法的布局中推导出来的。

【讨论】:

  • 你能解释一下为什么 decltype(1+2) 不应该是const int吗?
  • @user814628 为什么会这样?加法不行const.
  • 我想对我来说,(1+2) 保持不变感觉更自然,因为它是一个临时结果。
  • c不也是一个表达式吗?
  • @Jean-BaptisteYunès 是的。 decltype 只是有一个特殊情况:decltype(expr) 给出表达式 expr except 的类型和值类别,如果该表达式是一个未加括号的标识符(+ 一些其他例外),在这种情况下它做一些不同的事情(给出变量的declared type,而不是表达式在任何其他上下文中的类型和类别)。
【解决方案2】:

我找到了一个很好的描述here。它描述了两者之间的区别:

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-&gt;x) 既不是 id 表达式也不是成员访问表达式,因此不表示命名对象。 [13]

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

【讨论】:

  • 它还包含我前段时间所做的编辑......关于函数调用特殊情况。其他人也需要将这些修改应用于您引用的文章(我目前不想这样做)。
  • 而不是decltype((e)),你为什么不能只做decltype(e)&amp;
猜你喜欢
  • 2011-03-07
  • 2020-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-30
  • 1970-01-01
相关资源
最近更新 更多