keiloda
keiloda

Reputation: 57

Overloading of operators with class instance as right-hand side

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;
}    

Upvotes: 1

Views: 545

Answers (1)

Anton Savin
Anton Savin

Reputation: 41301

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
}

Upvotes: 2

Related Questions