我正在阅读 维基百科上关于
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)
是一个表达式,在本例中是一个 lvalue 表达式,其值与变量 c
的值相同。并且两者被
decltype
区别对待。例如,考虑 decltype(1+2)
,这也是采用 表达式 的示例。碰巧您的示例是表达式的“简单”版本:仅命名单个变量,并且没有任何令人兴奋的事情。
这是您通常只有在合理化语言规范的微妙部分时才真正关心的差异之一;不过,正如您所指出的,它在这种情况下具有相当显着的实际效果。
请注意,这里没有
operator用法。这一切都只是从语法布局中的推论。