Operator = overloading with templates


December 2018


86 time


Seriously, I looked at similar examples, but I still do not get why it is not working. I am having trouble with overloading the = operator.

I get the two following errors:

  1. error C2955: 'Matrix' : use of class template requires template argument list
  2. error C2244: 'Matrix::operator =' : unable to match function definition to an existing declaration

May someone please explain what is wrong?

Thanks to all


template<typename T>
class Matrix
    Matrix(int numberRows, int numberColumns);
    void asgValue(T value, int row, int column);
    T getValue(int row, int column);
    Matrix<T>& operator= (const Matrix<T>& rhs);
    friend Matrix<T>& operator+ (const Matrix<T>& lhs, const Matrix<T>& rhs);
    T **twoDarray;
    int nbrRows;
    int nbrColumns;

#include "Matrix.inl"


//Matrix<T>& Matrix<T>::operator= (const Matrix<T>& rhs)
template<typename T>
Matrix<T>& Matrix::operator= (const Matrix<T>& rhs)
    for (int i = 0; i < nbrRows; i++)
        for (int j = 0; j < nbrColumns; j++)
            twoDarray[i][j] = rhs.twoDarray[i][j];

    return *this;

1 answers


You need template parameters in the name of the function being defined.

template<typename T>
Matrix<T>& Matrix<T>::operator= (const Matrix<T>& rhs)
               // ^ here

You are required to write <T>, although it doesn't add to the expressiveness of the language — the arguments before :: cannot be anything other than the entire class template parameter list in the original order and without any modifications. It is what it is.