decltype
Version >= C++ 11
产生其操作数的类型,不进行评估。
-
如果操作数
e是没有任何附加括号的名称,则decltype(e)是e的声明类型。int x = 42; std::vector<decltype(x)> v(100, x); // v is a vector<int> -
如果操作数
e是没有任何附加括号的类成员访问,则decltype(e)是所访问成员的声明类型。struct S { int x = 42; }; const S s; decltype(s.x) y; // y has type int, even though s.x is const -
在所有其他情况下,
decltype(e)产生表达式e的类型和值类别 ,如下所示:- 如果
e是T类型的左值,则decltype(e)是T&。 - 如果
e是T类型的 x 值,则decltype(e)是T&&。 - 如果
e是T的 prvalue,则decltype(e)是T。
这包括带有无关括号的情况。
int f() { return 42; } int& g() { static int x = 42; return x; } int x = 42; decltype(f()) a = f(); // a has type int decltype(g()) b = g(); // b has type int& decltype((x)) c = x; // c has type int&, since x is an lvalue - 如果
Version >= C++ 14
特殊形式 decltype(auto) 使用 decltype 的类型推导规则而不是 auto 的类型推导规则,从其初始化器或其定义中的 return 语句中的函数的返回类型推导出变量的类型。
const int x = 123;
auto y = x; // y has type int
decltype(auto) z = x; // z has type const int, the declared type of x