您当前的位置:首页 > 计算机 > 编程开发 > VC/VC++

C++11 auto和decltype关键字

时间:03-07来源:作者:点击数:

可以用 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, int, 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.5101

第 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;
}
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门