decltype作为操作符,用于获取表达式的数据类型。C++11标准引入decltype,主要是为泛型编程而设计。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| #include <iostream> struct A { double x; }; const A* a; decltype(a->x) y; decltype((a->x)) z = y; template<typename T, typename U> auto add(T t, U u) -> decltype(t + u) // 返回类型依赖于模板形参 { return t+u; } int main() { int i = 33; decltype(i) j = i * 2; std::cout << "i = " << i << ", " << "j = " << j << '\n'; auto f = [](int a, int b) -> int { return a * b; }; decltype(f) g = f; i = f(2, 2); j = g(3, 3); std::cout << "i = " << i << ", " << "j = " << j << '\n'; }
|