我有一个类模板和一个操作符模板,需要访问它的私有字段。我可以交一个模板朋友:
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>
交友,而不为A<double>
的operator==<int>
交友?
发布于 2016-05-15 09:21:31
如果friend
有问题,那么在定义A
类之前,将声明向前推进。
template <typename T>
bool operator== (const A<T>& a, const A<T>& b);
然后,您可以更清楚地friend
它。完全解决方案(ideone):
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;
}
发布于 2016-05-15 09:08:26
是的你可以。语法如下:
template <typename T>
class A {
int x;
friend bool operator==<>(const A& a, const A& b);
};
并将您的operator==
定义(或仅仅是一个声明)放在A
类之前。
https://stackoverflow.com/questions/37236354
复制相似问题