jeudi 30 juin 2016

Making two types of same template compatible

I do not know how to name the problem that I am facing. So I have a template class for matrices to accept different types e.g. int, double and other stuff. My problem is if I want to work on to different instance type of the class, I can not get it to compile. Here is the definition of the add function which supposedly should add a matrix to the current instance.

template <class T>
void Matrix<T>::add(const Matrix &m) {
    for (int i = 0; i < this->rows; ++i) {
        for (int j = 0; j < this->cols; ++j) {
            this->mat[i][j] += m.at(i,j);
        }
    }
}

It works just fine e.g. if I add a Matrix<double> to Matrix<double> instance.

But I can not get it to work, adding a Matrix<int> to a Matrix<double> e.g:

Matrix<double> matA(2,2);
Matrix<int> matB(2,2);
matA.add(matB);

The compiler (g++ 4.8) complains:

error: no matching function for call to ‘Matrix<double>::add(Matrix<int>&)

What can be the workaround?

Aucun commentaire:

Enregistrer un commentaire