decltype关键字

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值