操作员的特定于朋友的模板实例化

Friend specific template instantiation of operator

本文关键字:实例化 朋友 于朋友 操作员      更新时间:2023-10-16

我有一个类模板和一个需要访问其私有字段的运算符模板。我可以交一个模板朋友:

template <typename T>
class A {
    int x;
    template <typename U>
    friend bool operator==(const A<U>& a, const A<U>& b);
};
template <typename T>
bool operator== (const A<T>& a, const A<T>& b) {
    return a.x == b.x;
}
int main() {
    A<int> x, y;
    x == y;
    return 0;
}

但有可能只让operator==<T>成为A<T>的朋友,而不让operator==<int>成为A<double>的朋友吗?

如果friend有问题,则在定义A类之前,将声明提前。

template <typename T>
bool operator== (const A<T>& a, const A<T>& b);

然后你可以更清楚地friend它。完整解决方案(视频):

template <typename T>
class A;
// declare operator== early (requires that A be introduced above)
template <typename T>
bool operator== (const A<T>& a, const A<T>& b);
// define A
template <typename T>
class A { 
    int x;
    // friend the <T> instantiation
    friend bool operator==<T>(const A<T>& a, const A<T>& b);
};
// define operator==
template <typename T>
bool operator== (const A<T>& a, const A<T>& b) { 
    return a.x == b.x;
}

可以。语法如下:

template <typename T>
class A {
    int x;
    friend bool operator==<>(const A& a, const A& b);
};

并将operator==定义(或只是一个声明)放在A类之前。