C++ 中的 auto 和 decltype 是什麼?
Auto 是 C++11 及更高版本中的一個關鍵字,用於自動型別推導。型別推斷或推導是指程式語言中表達式資料型別自動檢測。它是某些強型別靜態語言中存在的功能。例如,您想建立一個迭代器來迭代向量,您可以簡單地為此目的使用 auto。
示例
#include<iostream> #include<vector> using namespace std; int main() { vector<int> arr(10); for(auto it = arr.begin(); it != arr.end(); it ++) { cin >> *it; } return 0; }
在上面的程式中,它將自動獲取型別 std::vector<int>::iterator。
decltype 型別說明符會生成指定表示式的型別。與根據分配給變數的值推導型別的 auto 不同,decltype 會根據傳遞給它的表示式推導型別。decltype 返回的值可以直接用於定義另一個變數。例如,上面的程式碼可以使用 decltype 重寫如下:
示例
#include <iostream> #include <vector> using namespace std; int main() { vector<int> arr(10); for (decltype(arr.begin()) it = arr.begin(); it != arr.end(); it++) { cin >> *it; } return 0; }
請注意,decltype 表示的型別可能與 auto 推導的型別不同。您可以在這篇關於 C++ 型別推導的 12 頁解釋中閱讀更多關於這些細微差異的資訊:-http://thbecker.net/articles/auto_and_decltype/section_01.html
廣告