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