C++11 新特性之 decltype关键字
时间:2014-06-14 14:50:28
收藏:0
阅读:256
decltype关键字用于查询表达式的类型。与其他特性结合起来之后会有意想不到的效果。
decltype的语法是
decltype (expression)
实例:
#include <iostream>
#include <typeinfo>
using namespace std;
int main()
{
int i;
double d;
float f;
struct A
{
int i;
double d;
};
decltype(i) i1;
cout << typeid(i1).name() << endl; //g++编译器下输出i ,对应int类型
decltype(d) d1;
cout << typeid(d1).name() << endl;//输出d, double
decltype(f) f1;
cout << typeid(f1).name() << endl;//输出f,float
A *a = new A;
decltype(a->i) i2;
cout << typeid(i2).name() << endl; //输出i, int
decltype(a->d) d2;
cout << typeid(d2).name() << endl; //输出d,double
return 0;
}decltype在模板编程中的用处,举个例子,
template <class T, class U>
??? add(T t, U u)
{
return t+u;
}问题在于无法知道t+u返回的实际类型
解决方法:利用__typeof__扩展编写相当难看的代码
template <class T, class U>
__typeof__(*(T*)0 + *(U*)0) add(T t, U u)
{
return t+u;
}而在C++11中,我们可以使用auto关键字与decltype配合
#include <iostream>
#include <typeinfo>
using namespace std;
template <class T, class U>
auto add(T t, U u) ->decltype(t+u)
{
return t+u;
}
int main()
{
auto r = add(1, 1.0);
cout << typeid(r).name() << endl;
return 0;
}
评论(0)