Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return type unknown for template classes

Tags:

c++

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

What should be "something" here???

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

like image 776
Tilak Raj Singh Avatar asked Jan 13 '23 13:01

Tilak Raj Singh


1 Answers

You can handle both those issues with C++11's auto return type syntax the generous assistance of @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...
}

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

like image 77
Drew Dormann Avatar answered Jan 22 '23 16:01

Drew Dormann