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???
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With