C++11 auto和decltype关键字
发布时间:2020-12-16 07:40:52 所属栏目:百科 来源:网络整理
导读:可以用 auto 关键字定义变量,编译器会自动判断变量的类型。例如: auto i =100; // i 是 intauto p = new A(); // p 是 A*auto k = 34343LL; // k 是 long long 有时,变量的类型名特别长,使用 auto 就会很方便。例如: map string,int,greater string mp;f
可以用 auto 关键字定义变量,编译器会自动判断变量的类型。例如:
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,greater<string> >::iterator。 decltype 关键字可以用于求表达式的类型。例如: 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* 。auto 和 decltype 可以一起使用。例如: #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; }程序的输出结果如下: 101.5 101 第 12 行告诉编译器,add 的返回值类型是 decltype(x+y) ,即返回值的类型和x+y 这个表达式的类型一致。编译器将 add 实例化时,会自动推断出x+y 的类型。在 C++11 中,函数返回值若为 auto,则需要和 decltype 配合使用。在 C++14 中,则可以不用 decltype,例如下面的程序没有问题: auto add (int a,int b) { int i = a + b; return i; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |