1

I'm trying to do overload to * operator in my Matrix class.

I have one that make it if it is Matrix*something, (int, double...)

i'm searching for one that make it for the opposite side i.e something*Matrix

this is what i tried

template<class T>
bool operator*(Matrix<T>& other ){
Matrix<T> mat(other.rows,other.columns);
for(int i=0;i<other.rows;i++){
    for(int j=0;j<other.columns;j++){
        T temp=other.get(i,j);
        temp=temp*(this);
        mat.set(i,j,temp);
    }
}
return mat;
}    

and this is what works for Matrix*something

 Matrix<T>& operator*(const T & num){
    Matrix<T> mat(rows,columns);
    for(int i=0;i<rows;i++){
        for(int j=0;j<columns;j++){
            T temp=(matrix[i][j]);
            temp=temp*num;
            mat.set(i,j,temp);
        }
    }
    return mat;
}    
Anton Savin
  • 40,838
  • 8
  • 54
  • 90
keiloda
  • 57
  • 4

1 Answers1

2

You should make it a non-member, that is you write outside of Matrix class:

template<class T>
Matrix<T> operator*(const T& num, const Matrix<T>& mat) {
    return mat * num; // invoke existing implementation of Matrix * something
}

Note that operator* should return result by value. There is a bug in your implementation, you return dangling reference to a local variable mat.

Note that this form requires num to be of type T so if, like in your example, you have

Matrix<Rational> mat;
mat = 3 * mat;

it won't compile because 3 is not Rational.

What you can do is use identity trick to put num parameter in non-deduced context, so it will be converted from int to Rational:

template<class T>
Matrix<T> operator*(typename boost::mpl::identity<T>::type const& num, const Matrix<T>& mat) {
    return mat * num; // invoke existing implementation of Matrix * something
}

Where identity is just

template<typename T> 
struct identity { typedef T type; };

Or you can do just

template<class T, class U>
Matrix<T> operator*(const U& num, const Matrix<T>& mat) {
    return mat * num; // invoke existing implementation of Matrix * something
}
Community
  • 1
  • 1
Anton Savin
  • 40,838
  • 8
  • 54
  • 90
  • i tried this and i got some compilation error main.cpp:71:5: error: no match for ‘operator*’ (operand types are ‘int’ and ‘Matrix’) m=3*m; ^ main.cpp:71:5: note: candidate is: In file included from main.cpp:3:0: Matrix.hpp:229:12: note: template Matrix& operator*(const T&, const Matrix&) Matrix& operator*(const T& num,const Matrix &matr){ ^ Matrix.hpp:229:12: note: template argument deduction/substitution failed: main.cpp:71:6: note: deduced conflicting types for parameter ‘T’ (‘int’ and ‘Rational’) m=3*m; ^ – keiloda Jan 15 '15 at 07:51
  • @keiloda It's kinda self-explanatory - `3` is `int` and not `Rational` so types mismatch. – Anton Savin Jan 15 '15 at 08:02