C++——decltype

decltype 类型说明符给定一个指定表达式的类型。 与 auto 关键字一起 decltype 类型说明符,主要,编写模板库的开发人员很有用。 使用 auto ,并声明返回类型的模板函数的 decltype 取决于其模板参数的类型。 或者,使用 auto 和 decltype 声明包装调用另一个模板函数,然后返回该包装函数的返回类型。

demo:与auto联用

decltype预测出返回的类型,搭配上&&右引用的完全转发。

template<typename T1, typename T2>
auto MyFun(T1&& t1, T2&& t2) -> 
	decltype(forward<T1>(t1) + forward<T2>(t2))
{
	return forward<T1>(t1) + forward<T2>(t2);
};

对于简单结果来说 直接 调用MyFun()函数即可。

若是同类调用MyFun() 需要重构操作符operator()

这里就是operator+

demo如下:

class X
{
public:
	X()
	{
		x = 0;
	}
	X(int val)
		:x(val){}
	X operator +(const X & other)
	{
		cout << "operator +" << endl;
		x += other.x;
		return *this;
	}
	int x;
};
void main()
{
	X i(1) ;
	X tmp(2);
	cout << MyFun(tmp,i).x << endl;;
	system("pause");
}

以下原型声明一个替代函数声明的语法。 请注意 const 和 volatile 限定符和 throw异常规范 是可选的。

例如在异常规范加上throw()即可 

template<typename T1, typename T2>
auto Plus(T1&& t1, T2&& t2)  throw() -> 
	decltype(forward<T1>(t1) + forward<T2>(t2))
{
	return forward<T1>(t1) + forward<T2>(t2);

};

用法如下

try
{
	cout << Plus(tmp,i).x << endl;
}
catch(...)
{
	cout << "catch error" << endl;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值