假设我正在为二叉树创建一个类 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;
};
这意味着 bar
是 foo
的 friend 不管bar
的模板参数。 bar<char>
, bar<int>
, bar<float>
,以及任何其他 bar
将成为 foo<char>
的 friend .
template<typename T>
struct foo {
friend class bar<T>;
};
这意味着 bar
是 foo
的 friend 当bar
的模板参数匹配 foo
的。仅限 bar<char>
将成为 foo<char>
的 friend .
在你的情况下,friend class bar<T>;
应该足够了。
关于c++ - 类模板与模板类 friend ,这里到底发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8967521/