类模板与模板类朋友,这里到底发生了什么?

2021-12-09 00:00:00 class templates c++

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

Let's say I'm creating a class for a binary tree, BT, and I have a class which describes an element of the tree, BE, something like

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:
...
};

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

This appears to work; however I have questions about what's going on underneath.

我最初尝试将朋友声明为

I originally tried to declare the friend as

template<class T> friend class BT;

然而,这里似乎有必要使用 U(或除 T 以外的其他东西),这是为什么呢?这是否意味着任何特定的 BT 是任何特定 BE 类的朋友?

however it appears necessary to use U (or something other than T) here, why is this? Does it imply that any particular BT is friend to any particular BE class?

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

The IBM page on templates and friends has examples of different type of friend relationships for functions but not classes (and guessing a syntax hasn't converged on the solution yet). I would prefer to understand how to get the specifications correct for the type of friend relationship I wish to define.

推荐答案

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

不允许,因为模板参数不能相互遮蔽.嵌套模板必须具有不同的模板参数名称.

Is not allowed because template parameters cannot shadow each other. Nested templates must have different template parameter names.

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

这意味着 barfoo 的朋友,而不管 bar 的模板参数如何.barbarbar 和任何其他 bar 都是朋友foo.

This means that bar is a friend of foo regardless of bar's template arguments. bar<char>, bar<int>, bar<float>, and any other bar would be friends of foo<char>.

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

这意味着当 bar 的模板参数匹配 foo 的模板参数时,barfoo 的朋友.只有 barfoo 的朋友.

This means that bar is a friend of foo when bar's template argument matches foo's. Only bar<char> would be a friend of foo<char>.

在您的情况下,friend class bar; 应该就足够了.

In your case, friend class bar<T>; should be sufficient.

相关文章