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