LNK2019 的一种情况,需要限定友元所作用的实例化
Written on April 21st , 2021 by Kong Wei Hang正好在实现一个Vector2类型:
template<typename T>
struct Vector2;
template<typename T>
Vector2<T> operator+(const Vector2<T>& v1, const Vector2<T>& v2);
template<typename T>
Vector2<T> operator-(const Vector2<T>& v1, const Vector2<T>& v2);
template<typename T>
struct Vector2 final {
T x;
T y;
public:
friend Vector2<T> operator+(const Vector2<T>& v1, const Vector2<T>& v2);
friend Vector2<T> operator-(const Vector2<T>& v1, const Vector2<T>& v2);
}
会提示错误
LNK2019 unresolved external symbol referenced in function operator namespace
之后在实现内改为:
public:
friend Vector2<T> operator+ <>(const Vector2<T>& v1, const Vector2<T>& v2);
friend Vector2<T> operator- <>(const Vector2<T>& v1, const Vector2<T>& v2);
上面的代码将运算符的friend限制在相应的Vector实例化上,即operator+
reference: https://stackoverflow.com/questions/35819831/friend-template-overloaded-operator-unresolved-external-symbol
Feel free to share!