I am new to C++ and got this error for hours and I hope someone can help me with this.
So basically I have got 2 classes: Matrix
,DenseMatrix
with DenseMatrix
being the subclass of Matrix
.
For some simple mathematical operations like adding two matrices which are always the same for any type of matrix, I wanted to implement a function in the class Matrix
.
T &mul(const Matrix &other);
The idea is that calling mul
on a subclass (e.g DenseMatrix
), the result will also be a DenseMatrix
. However the other matrix does not need to be the same class, just any subclass of Matrix
. That's why I use generic types and my classes are defined like this:
class DenseMatrix : public Matrix<DenseMatrix>
class OtherMatrix: public Matrix<OtherMatrix>
class OtherMatrix2: public Matrix<OtherMatrix2>
...
So that calling mul
will return a matrix of the same type and the argument is simply a Matrix without diamond-brackets.
Now the Problem is that I am getting the following error:
DenseMatrix mat{6,6};
DenseMatrix mat2{6,6};
mat.add(mat2);
>>> undefined reference to `Matrix<DenseMatrix>::add(Matrix<DenseMatrix> const&, int)'
I was thinking that maybe I need to introduce a second generic type for the argument of the function but I am not sure how to do this.
I am very happy if someone could help me with this one.
Matrix.h:
template <typename T>
class Matrix {
T &add(const Matrix &other, int threads = 1);
}
Matrix.cpp:
#include "Matrix.h"
template<typename T>
T &Matrix<T>::add(const Matrix &other, int threads) {
std::cout << "ADDING";
return *this;
}
DenseMatrix.h:
class DenseMatrix : public Matrix<DenseMatrix> {
}