gpt4 book ai didi

c++ - 类模板与模板类 friend ,这里到底发生了什么?

转载 作者:IT老高 更新时间:2023-10-28 12:08:38 26 4
gpt4 key购买 nike

假设我正在为二叉树创建一个类 BT,并且我有一个描述树元素的类 BE,类似于

template<class T> class BE {
T *data;
BE *l, *r;
public:
...
template<class U> friend class BT;
};

template<class T> class BT {
BE<T> *root;
public:
...
private:
...
};

这似乎有效;但是我对下面发生的事情有疑问。

我最初试图将 friend 声明为

template<class T> friend class BT;

然而这里似乎有必要使用 U(或 T 以外的其他东西),这是为什么呢?它是否暗示任何特定的 BT 是任何特定 BE 类的 friend ?

关于模板和好友的 IBM 页面提供了函数但没有类的不同类型好友关系的示例(并且猜测语法尚未收敛到解决方案上)。我更愿意了解如何为我希望定义的 friend 关系类型获得正确的规范。

最佳答案

template<class T> class BE{
template<class T> friend class BT;
};

不允许,因为模板参数不能相互影响。嵌套模板必须具有不同的模板参数名称。


template<typename T>
struct foo {
template<typename U>
friend class bar;
};

这意味着 barfoo 的 friend 不管bar的模板参数。 bar<char> , bar<int> , bar<float> ,以及任何其他 bar将成为 foo<char> 的 friend .


template<typename T>
struct foo {
friend class bar<T>;
};

这意味着 barfoo 的 friend 当bar的模板参数匹配 foo的。仅限 bar<char>将成为 foo<char> 的 friend .


在你的情况下,friend class bar<T>;应该足够了。

关于c++ - 类模板与模板类 friend ,这里到底发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8967521/

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