auto i =100; // i 是 int auto p = new A(); // p 是 A* auto k = 34343LL; // k 是 long long有时,变量的类型名特别长,使用 auto 就会很方便。例如:
map <string, int, greater <string> >mp; for( auto i = mp.begin(); i != mp.end(); ++i) cout << i -> first << ", " << i -> second;编译器会自动判断出 i 的类型是 map<string, int, greater<string> >::iterator。
int i; double t; struct A { double x; }; const A* a = new A(); decltype(a) x1; //x1 是 A* decltype(i) x2; //x2 是 int decltype(a -> x) x3; // x3 是 double在上面的例子中,编译器自动将 decltype (a) 等价为
A*
,因为编译器知道 a 的类型是A*
。#include <iostream> using namespace std; struct A { int i; A(int ii) : i(ii) {} }; A operator + (int n, const A & a) { return A(a.i + n); } template <class T1, class T2> auto add(T1 x, T2 y) -> decltype(x + y) { return x + y; } int main() { auto d = add(100, 1.5); // d 是 double 类型,d = 101.5 auto k = add(100, A(1)); // k 是 A 类型,因为表达式“100+A(1)”是A类型的 cout << d << endl; cout << k.i << endl; return 0; }程序的输出结果如下:
decltype(x+y)
,即返回值的类型和x+y
这个表达式的类型一致。编译器将 add 实例化时,会自动推断出x+y
的类型。auto add (int a, int b) { int i = a + b; return i; }
Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有