返回类型为模板类未知 [英] return type unknown for template classes

查看:120
本文介绍了返回类型为模板类未知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个矩阵类,并且想要添加不同数据类型的两个矩阵。像int和double返回类型的matrice应该是double。我该怎么办?
这是我的代码

I have created a matrix class and want to add two matrices of different data types. Like for int and double return type of matrice should be double. How can I do that??? This is my code

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

这里应该是什么?

还有什么应该做,这样我可以使用resoutside if else语句

Also what should be done so that I can use "res" outside if else statement???

推荐答案

您可以使用 C ++ 11的自动返回类型语法

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 ++通常产生的两个模板类型添加时。

With this syntax, your "something" will be the type C++ normally produces when the two template types are added.

这篇关于返回类型为模板类未知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆