Reputation: 2956
I have a matrix class defined this way:
template<int M, int N, typename T>
class Matrix
{
typedef Matrix<M, N, T> MTYPE;
/*...*/
};
I have to implement the matrix multiplication but I do not know how to do the operator overriding..
Something like
MTYPE operator *(MTYPE& m) { /*...*/ }
Would accept only a N*M matrix. So how can I overcome this problem?
Upvotes: 2
Views: 2087
Reputation: 12817
You'll need to create a templated operator, either inside or outside of the class.
For example, to multiply a N x M by a M x M you might want to do:
template <int N, int M, class T>
friend Matrix<N, M, T> operator*(const Matrix<N, M, T> &lhs, const Matrix<M, M, T> &rhs);
Other versions look similar. It'd probably most useful to define this outside of the class.
To multiply a (N1 x M) by (M x N2) you'd do:
template<int N1, int N2, int M, class T>
friend Matrix<N1, N2, T> operator*(const Matrix<N1, M, T> &lhs, const Matrix<M, N2, T> &rhs);
Upvotes: 3
Reputation: 4953
As has been pointed out in a comment, *= doesn't make sense for non-square matrices.
For the general case,
template<int M, int N, typename T>
class Matrix
{
typedef Matrix<M, N, T> MTYPE;
/*...*/
public:
template<int L>
Matrix<M,L,T> operator*(const Matrix<N,L,T>& second) const
{
Matrix<M,L,T> result;
for(...)
for(...)
for(...)
// ...
return result;
}
};
Or, if you prefer, use a free function operator* with two parameters (and template arguments M,N,L, and T), and make it a friend of your matrix class.
Upvotes: 3