版权声明:本文为博主原创文章,未经博主同意不得转载。 https://blog.csdn.net/lr982330245/article/details/30728131
decltypekeyword用于查询表达式的类型。与其它特性结合起来之后会有意想不到的效果。
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在模板编程中的用处,举个样例,
问题在于无法知道t+u返回的实际类型template <class T, class U> ?
?? add(T t, U u) { return t+u; }
解决方法:利用__typeof__扩展编写相当难看的代码
template <class T, class U>
__typeof__(*(T*)0 + *(U*)0) add(T t, U u)
{
return t+u;
}
而在C++11中。我们能够使用autokeyword与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;
}