Ryan J. Shrott
Ryan J. Shrott

Reputation: 602

How to overload an operator with a friend function in a generic class?

I have written a matrix class. I have overloaded the operator+, so that the user can write: matrix + 2. I would like the user to also write: 2 + matrix.

For the standard format (i.e. the object invoking 2) I have written a standard operator overloading function. It works.

template<typename T>
Matrix<T> Matrix<T>::operator+(const T& rhs) const
{
    Matrix result(rows, cols, 0.0);
    for (unsigned i = 0; i < rows; ++i)
    {
        for (unsigned j = 0; j < cols; ++j)
        {
            result(i,j) = (*this)(i, j) + rhs;
        }
    }
    return result;
}

Now for the other order (i.e. 2 + matrix), I have written the friend function:

// Friend Functions that allow the user to write expressions in a different order 
    template<typename T>
    friend Matrix<T> operator+(const T& type, const Matrix<T>& matrix);

and implementation as:

template<typename T>
Matrix<T> operator+(const T& type, const Matrix<T>& matrix) 
{
    return matrix + type;
}

When I try to write 2 + matrix (in main()), I get some errors.

I have always had problems using friend functions with generic classes and frankly, I have never understood why it never works for me.

Could someone please explain what I am doing wrong here?

Errors I get:

IntelliSense: no operator "+" matches these operands operand types are: int + Matrix

Severity Code Description Project File Line Error C2244 'Matrix::operator +': unable to match function definition to an existing declaration

Upvotes: 0

Views: 1391

Answers (2)

txtechhelp
txtechhelp

Reputation: 6777

It looks like it's just a template deduction error; that is to say that your compiler can't deduce the proper function based on the templated friend function.

Since your friend function is a simple function, you could just declare it in your class/header and the compiler should be able to deduce it properly (as well as possibly inline it if optimizations are turned on); just declare the friend function in your header like such:

friend Matrix operator+(const T& type, const Matrix& matrix)
{
    return matrix + type;
}

You don't need to specify the template keyword since it's within your template specialized class.

Hope that can help.

Upvotes: 1

R Sahu
R Sahu

Reputation: 206577

You can fix the problem simply by changing the member function to const.

template<typename T>
Matrix<T> Matrix<T>::operator+(const T& rhs) const
{
   ...
}

Upvotes: 1

Related Questions