LNK2019 的一种情况,需要限定友元所作用的实例化

正好在实现一个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+ 实例化仅限于访问Vector 实例化的私有成员。

reference: https://stackoverflow.com/questions/35819831/friend-template-overloaded-operator-unresolved-external-symbol

posted @ 2021-04-21 10:30  威化饼干  阅读(0)  评论(0编辑  收藏  举报