自動型別扣除
Version >= C++ 11
使用 auto
關鍵字進行型別推導與模板型別推導幾乎相同。以下是一些例子:
auto x = 27; // (x is neither a pointer nor a reference), x's type is int
const auto cx = x; // (cx is neither a pointer nor a reference), cs's type is const int
const auto& rx = x; // (rx is a non-universal reference), rx's type is a reference to a const int
auto&& uref1 = x; // x is int and lvalue, so uref1's type is int&
auto&& uref2 = cx; // cx is const int and lvalue, so uref2's type is const int &
auto&& uref3 = 27; // 27 is an int and rvalue, so uref3's type is int&&
差異概述如下:
auto x1 = 27; // type is int, value is 27
auto x2(27); // type is int, value is 27
auto x3 = { 27 }; // type is std::initializer_list<int>, value is { 27 }
auto x4{ 27 }; // type is std::initializer_list<int>, value is { 27 }
// in some compilers type may be deduced as an int with a
// value of 27. See remarks for more information.
auto x5 = { 1, 2.0 } // error! can't deduce T for std::initializer_list<t>
正如你所看到的,如果使用支撐初始化器,則會強制 auto 建立 std::initializer_list<T>
型別的變數。如果它無法推斷出 T
,則程式碼被拒絕。
當 auto
用作函式的返回型別時,它指定該函式具有尾隨返回型別 。
auto f() -> int {
return 42;
}
Version >= C++ 14
除了 C++ 11 中允許的自動使用外,C++ 14 還允許以下內容:
-
當用作沒有尾隨返回型別的函式的返回型別時,指定函式的返回型別應該從函式體中的 return 語句推匯出來(如果有的話)。
// f returns int: auto f() { return 42; } // g returns void: auto g() { std::cout << "hello, world!\n"; }
-
在 lambda 的引數型別中使用時,將 lambda 定義為通用 lambda 。
auto triple = [](auto x) { return 3*x; }; const auto x = triple(42); // x is a const int with value 126
特殊形式 decltype(auto)
使用 decltype
的型別演繹規則而不是 auto
的型別演繹規則。
int* p = new int(42);
auto x = *p; // x has type int
decltype(auto) y = *p; // y is a reference to *p
在 C++ 03 及更早版本中,auto
關鍵字作為從 C 繼承的儲存類說明符具有完全不同的含義。