简体   繁体   中英

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 (ie 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 (ie 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

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
{
   ...
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM