template <typename T>
class Matrix
{
/* parameters, construcor, destructor */
// I want to overload a "*" operator
// I need to overload "*" in such a way that it will take 2 Matrix objects
// of different types. And return a Matrix of another type.
// So, if I have Matrix<int> A, B; A*B will return an int type Matrix.
// If I have Matrix<int> A; Matrix<double> B; A*B must return double type Matrix;
// And if I have Matrix<int> A; Matrix<double> B; B*A must return double type Matrix;
// I want to return a Matrix object, so I declare a friend funvtion inside the class.
// if I understand correclty, it should be something like this:
template<typename R, typename C> friend Matrix<T> operator*(Matrix<R>& A, Matrix<C>& B);
// .......
// Now, how would I implement my function outside the class?
// Like this?
template <typename T>
template<typename R, typename C> Matrix<T> operator*(Matrix<R>& A, Matrix<C>& B){
Matrix<T> result ;
/*calculations happen*/
return result;
}
> So, if I have Matrix<int> A, B; A*B will return an int type Matrix.
> If I have Matrix<int> A; Matrix<double> B; A*B must return double type Matrix;
> And if I have Matrix<int> A; Matrix<double> B; B*A must return double type Matrix;
#include <type_traits>
template <typename T> class Matrix
{
// http://en.cppreference.com/w/cpp/types/common_typetemplate< typename A, typename B >
friend Matrix< typename std::common_type<A,B>::type > operator*( const Matrix<A>&, const Matrix<B>& );
// .......
private: int test = 10 ;
};
template< typename A, typename B >
Matrix< typename std::common_type<A,B>::type > operator*( const Matrix<A>& a, const Matrix<B>& b )
{
Matrix< typename std::common_type<A,B>::type > result ;
/*calculations happen*/
result.test = a.test * b.test ;
return result ;
}
int main()
{
Matrix<short> s ;
Matrix<int> i ;
Matrix<double> d ;
Matrix<int> result = s * i ;
// http://en.cppreference.com/w/cpp/types/is_samestatic_assert( std::is_same< decltype( d * result ), Matrix<double> >::value,
"expected the common type to be double" ) ;
}