C ++类模板与模板类的朋友,真正在这里发生了什么? [英] C++ class template with template class friend, what's really going on here?

查看:171
本文介绍了C ++类模板与模板类的朋友,真正在这里发生了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我为一个二叉树创建一个类,BT,并且我有一个描述树的元素的类,BE,例如

let's say I'm creating a class for a binary tree, BT, and a I have 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它是否意味着任何特定的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 class 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 foo bar 的模板参数匹配 foo 。只有 bar 才是 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> ;;

这篇关于C ++类模板与模板类的朋友,真正在这里发生了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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