I am writing a template class for a matrix and I want to overload its operator*
.
Matrix.h:
(include guard)
namespace foo {
template<typename T, unsigned int D>
class Matrix {
...
public:
Matrix<T, D>& operator*=(const Matrix<T, D>& rhs) {
(multiplication stuff)
return *this;
}
};
template<typename T, unsigned int D>
Matrix<T, D> operator*(Matrix<T, D> lhs, const Matrix<T, D>& rhs) {
lhs *= rhs;
return lhs;
}
template class Matrix<float, 3>;
}
(include guard)
And then I use this class as a super class for e.g a Matrix3x3<float>
.
But when I call foo::Matrix3x3f m3 = m1 * m2
, where m1
and m2
are already initialized matrices, I get the following error message during compilation:
C:/Dev/Foo/main.cc:20: undefined reference to `foo::Matrix<float, 3u> operator*<float, 3u>(foo::Matrix<float, 3u>, foo::Matrix<float, 3u> const&)'
EDIT:
main.cc
#include "Matrix.h"
int main(int argc, char** argv) {
foo::Matrix3x3<float> m1 = foo::Matrix3x3<float>::InitIdentity();
foo::Matrix3x3<float> m2 = foo::Matrix3x3<float>::InitIdentity();
foo::Matrix3x3<float> m3 = m1 * m2;
return 0;
}
Where InitIdentity is a static method that created an identity matrix.
EDIT 2:
I've split the class into declaration in Matrix.h
and definition in Matrix.cc
. But for the template to work I did add the following at the end of both files for explicit template instantiation:
Matrix.h
extern template class Matrix<float, 3>;
Matrix.cc
template class Matrix<float, 3>;
Matrix3x3.h
extern template class Matrix3x3<float>;
typedef Matrix3x3<float> Matrix3x3f;
Matrix3x3.cc
template class Matrix3x3<float>;
As I've read here:
https://stackoverflow.com/a/1724632/9369168
and here
Since in know which types and sizes the matrices are going to use I thought this would be file.