class with templates. Overloading parameters.

Hello! I'm new to C++. Need help with syntax. THX in advance!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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;
   }
Last edited on
> 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;

Use std::common_type<> http://en.cppreference.com/w/cpp/types/common_type

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <type_traits>

template <typename T> class Matrix
 {
    // http://en.cppreference.com/w/cpp/types/common_type
    template< 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_same
    static_assert( std::is_same< decltype( d * result ), Matrix<double> >::value,
                   "expected the common type to be double" ) ;
}

http://coliru.stacked-crooked.com/a/bf9d7b05f6e68f63
Topic archived. No new replies allowed.