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

Class template with template class friend, what#39;s really going on here?(类模板与模板类朋友,这里到底发生了什么?)
本文介绍了类模板与模板类朋友,这里到底发生了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

假设我正在为二叉树创建一个类 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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Bring window to front -gt; raise(),show(),activateWindow() don’t work(把窗户放在前面 -raise(),show(),activateWindow() 不起作用)
How to get a list video capture devices NAMES (web cameras) using Qt (crossplatform)? (C++)(如何使用 Qt(跨平台)获取列表视频捕获设备名称(网络摄像机)?(C++))
How to compile Qt as static(如何将 Qt 编译为静态)
C++ over Qt : Controlling transparency of Labels and Buttons(C++ over Qt:控制标签和按钮的透明度)
How to know when a new USB storage device is connected in Qt?(Qt如何知道新的USB存储设备何时连接?)
What is an event loop in Qt?(Qt 中的事件循环是什么?)