lundi 2 juillet 2018

Template friend function of template class

I am wondering how to make a function friend of a class and define the function outside class if the function's template arguments include but are not limited to the class's template arguments.

For example, I have the following template class and template friend function:

template<int N>  class Matrix;
template<typename T, int N> Matrix<N> operator*(const Matrix<N> &m1, const T &m2);

// class definition
template<int N>
class Matrix{
  template<typename T>
  friend Matrix<N> operator* (const Matrix<N> &m1, const T &m2);
};

// friend function definition
template<typename T, int N> Matrix<N> operator*(const Matrix<N> &m1, const T &m2)
{
  xxx
}

If I compile:

Matrix<3> m;
m * 1.0;

I would get the following error:

test.cc:(.text+0x1c7): undefined reference to `Matrix<3> operator*<double>(Matrix<3> const&, double const&)'
collect2: error: ld returned 1 exit status

Aucun commentaire:

Enregistrer un commentaire