与模板类的朋友一起创建类模板,这到底是怎么回事? [英] Class template with template class friend, what's really going on here?

查看:65
本文介绍了与模板类的朋友一起创建类模板,这到底是怎么回事?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在为二进制树 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;
};

这意味着 bar 是的朋友 foo 不管 bar 的模板参数如何。 bar< char> bar< int> bar< float> ,其他任何 bar 都是 foo< char> 的朋友。

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 是的朋友当 bar 的模板参数与 foo 的模板参数匹配时, foo 。只有 bar< char> foo< char> 的朋友。

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< T> ;; 就足够了。

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

这篇关于与模板类的朋友一起创建类模板,这到底是怎么回事?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆