decltype 是 C++ 程序设计语言中的一个关键字,用于在编译时确定表达式或变量的类型。它允许您在不实际评估表达式的情况下提取其类型。
为确定类型,编译器必须遍历一个核对表。假如有如下声明:
decltype(expression) var;
第一步:如果expression是一个没有用括号括起的标识符,则var的类型与该标识符的类型相同,包括const等限定符:
double x = 5.5;
double y = 7.7;
double& rx = x;
const double* pd;
decltype(x) w; //w is type double
decltype(rx) u = y; //u is type double&
decltype(pd) v; //v is type const double *
第二步:如果expression是一个函数调用,则var的类型与函数的返回类型相同:
long indeed(int x);
int indeed(int x, int y);
decltype(indeed(3)) m;//m is type long
注意:并不会实际调用函数,编译器通过查看函数的原型来获悉返回类型,而无需实际调用函数
第三步:如果expression是一个左值,并且是用括号括起的标识符,则var为指向其类型的引用:
double xx = 7.5;
decltype((xx)) r2 = xx;//r2 is double&
decltype (xx) w = xx;//w is double (Stage 1 match)
第四步:如果前面的条件都不满足,则var的类型与expression的类型相同:
int j = 3;
int& k = j;
int& n = j;
decltype(j + 6) i1;//i1 is type int
decltype(100L) i2;//i2 is type long
decltype(k + n) i3;//i3 is type int
如果需要多次声明,可结合使用typedef和decltype:
template<class T1, class T2>
void ft(T1 x, T2 y) {
typedef decltype(x + y) xytype;
xytype xpy = x + y;
xytype arr[10];
xytype& rxy = arr[2];
}
后置返回类型(trailing return type):
template<class T1, class T2>
?type? ft(T1 x, T2 y) {
return x + y;
}
decltype本身无法解决以上问题。
/*
double h(int x, int y) {
function body
}
*/
//后置返回类型
auto h(int x, float y)->double {
//function body
}
因此可如下解决最初问题:
template<class T1, class T2>
auto ft(T1 x, T2 y)->decltype(x+y) {
return x + y;
}