I have implemented a matrix class using CRTP. For the matrix multiplication, I would like to use a friend operator*
. The problem is that, according to this question and my own experience, I need to define the operator*
inside the class to make it work.
This means, however, that I have to re-use the class template parameters in the definition, which gives access only to one of the three matrices involved in the computation. I cannot seem to provide friendship to the others.
Code example:
template<template<unsigned, unsigned> class Child, unsigned M, unsigned N>
class BaseMatrix
{
// This works, but does not give access to rhs or to the return value
template<unsigned L>
friend Child<M, L> operator*(const BaseMatrix<Child, M, N>& lhs, const BaseMatrix<Child, N, L>& rhs)
{
Child<M, L> result;
result.v = lhs.v + rhs.v; // demo, of course
return result;
}
// This compiles, but does not do anything
template<template<unsigned, unsigned> class Child2, unsigned M2, unsigned N2, unsigned L>
friend Child2<M2, N2> operator*(const BaseMatrix<Child2, M2, L>&, const BaseMatrix<Child2, L, N2>&);
// This produces an ambiguous overload
template<unsigned L>
friend Child<M, N> operator*(const BaseMatrix<Child, M, L>& lhs, const BaseMatrix<Child, L, N>& rhs);
double v;
};
template<unsigned M, unsigned N>
class ChildMatrix : public BaseMatrix<ChildMatrix, M, N>
{
};
int main()
{
ChildMatrix<3, 4> a;
ChildMatrix<4, 5> b;
ChildMatrix<3, 5> c = a * b;
return 0;
}
How can I prevent the access violations to rhs.v
and to result.v
errors here?