Return type unknown for template classes

I created a matrix class and want to add two matrices of different data types. As for int and double return, the type of the matrix must be double. How can I do it??? This is my code.

template<class X> class Matrix { .......... ........ template<class U> Matrix<something> operator+(Matrix<U> &B) { if((typeid(a).before(typeid(Ba)))) Matrix<typeof(Ba)> res(1,1); else Matrix<typeof(a)> res(1,1); } 

What should be "something" here?

And what needs to be done so that I can use "res" outside if else statement ???

+4
source share
2 answers

You can handle both of these problems using syntax like C ++ 11 auto return generous help @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... } 

In this syntax, your β€œsomething” will be the C ++ type typically created when two types of templates are added.

+5
source

Try common_type :

 #include <type_traits> template <typename T> class Matrix { // ... template <typename U> Matrix<typename std::common_type<T, U>::type> operator+(Matrix<U> const & rhs) { typedef typename std::common_type<T, U>::type R; Matrix<R> m; // example // ... return m; } }; 
+4
source

All Articles