gpt4 book ai didi

c++ - 运算符的 friend 特定模板实例化

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:22:23 25 4
gpt4 key购买 nike

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

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> friend A<T>而不是制作operator==<int> A<double>的 friend ?

最佳答案

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

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

然后你就可以更清楚地加好友了。完整解决方案(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;
}

关于c++ - 运算符的 friend 特定模板实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37236354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com