我创建了一个矩阵类,想要添加两个不同数据类型的矩阵。像 int 和 double 返回类型的矩阵应该是 double。我怎样才能做到这一点??? 这是我的代码
template<class X>
class Matrix
{
..........
........
template<class U>
Matrix<something> operator+(Matrix<U> &B)
{
if((typeid(a).before(typeid(B.a))))
Matrix<typeof(B.a)> res(1,1);
else
Matrix<typeof(a)> res(1,1);
}
这里的“东西”应该是什么???
另外应该怎么做才能在 if else 语句之外使用“res”???
最佳答案
您可以使用 C++11 的自动返回类型语法 @DyP 的慷慨帮助来处理这两个问题 :)。
template<typename U>
Matrix <decltype(declval<X>()+declval<U>())> operator+(const Matrix<U> &B) const
{
Matrix< decltype( declval<X>() + declval<U>() ) > res;
// The rest...
}
使用此语法,您的“某物”将是添加两个模板类型时 C++ 通常生成的类型。
关于c++ - 模板类的返回类型未知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16226162/