As stated in the comments, your friend function declaration
friend Vector4<T> operator*(const Vector4<T>& l, const Vector4<T>& r);
declares a non-template function in the global namespace. When you instantiate e.g. Vector4<int>
, the function
Vector4<int> operator*(const Vector4<int>& l, const Vector4<int>& r)
is declared. Note that it's not a function template. (Also see [temp.friend])
Your Vector4.inl
then declares and defines a function template
template<typename T>
Vector4<T> operator*(const Vector4<T>& l, const Vector4<T>& r)
i.e. an overload of the former function. In the expression a * b
, overload resolution chooses the non-template operator*
over the template version (see [over.match.best]/1). This results in a linker error, as the non-template function hasn't been defined.
As I've almost fooled myself, a short remark:
template<typename T>
Vector4<T> operator*(const Vector4<T>& l, const Vector4<T>& r);
As this operator is a free function (a non-member function), these two lines declare a function template, much like
template<typename T>
Vector4<T> wup();
On the other hand,
template<typename T>
Vector4<T> Vector4<T>::operator*(const Vector4<T>& r)
{ /* ... */ }
defines a member function (non-template) of a class template (Vector4
).
One solution is to use forward-declarations and befriend only a specific specialization:
template<typename T>
class Vector4;
template<typename T>
Vector4<T> operator*(const Vector4<T>& l, const Vector4<T>& r);
template<typename T>
class Vector4
{
public:
T X;
T Y;
T Z;
T W;
Vector4();
Vector4(T X, T Y, T Z, T W);
~Vector4();
// compiler knows of some function template `operator*`,
// can name an specialization:
// ~~~~~~~~~~~~~~~~~~~~~~~~vvv
friend Vector4<T> operator*<T>(const Vector4<T>& l, const Vector4<T>& r);
};
template<typename T>
Vector4<T>::Vector4()
{
X = 0;
Y = 0;
Z = 0;
W = 0;
}
template<typename T>
Vector4<T>::Vector4(T X, T Y, T Z, T W)
{
this->X = X;
this->Y = Y;
this->Z = Z;
this->W = W;
}
template<typename T>
Vector4<T>::~Vector4()
{}
template<typename T>
Vector4<T> operator*(const Vector4<T>& l, const Vector4<T>& r)
{
return(Vector4<T>(l.X * r.X, l.Y * r.Y, l.Z * r.Z, l.W * r.W));
}
int main()
{
Vector4<float> a, b;
a = a * b;
}
Another solution would be to friend the whole operator*
template instead of a single specialization:
template<typename U>
friend Vector4<U> operator*(Vector4<U> const&, Vector4<U> const&);