auto (C++11) dùng cho suy diễn kiểu tự động. Type inference: tự động phát hiện kiểu dữ liệu của biểu thức. Ví dụ: tạo iterator cho vector, dùng auto.
Ví dụ 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;
}
it tự động nhận kiểu std::vector<int>::iterator.
decltype cho ra kiểu của biểu thức xác định. Khác với auto suy diễn từ giá trị gán, decltype suy diễn từ biểu thức. Kết quả dùng định nghĩa biến khác. Ví dụ viết lại trên dùng decltype:
Ví dụ 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;
}
Lưu ý: kiểu decltype có thể khác kiểu auto. Xem chi tiết tại thbecker.net.