c++ - 类模板与模板类 friend ,这里到底发生了什么?

标签 c++ class templates

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

这意味着 barfoo 的 friend 不管bar的模板参数。 bar<char> , bar<int> , bar<float> ,以及任何其他 bar将成为 foo<char> 的 friend .


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

这意味着 barfoo 的 friend 当bar的模板参数匹配 foo的。仅限 bar<char>将成为 foo<char> 的 friend .


在你的情况下,friend class bar<T>;应该足够了。

关于c++ - 类模板与模板类 friend ,这里到底发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8967521/

相关文章:

c++ - 为什么我不能将C++转换运算符作为非成员函数重载于类之外?

c++ - 重载运算符 C++,复数?

c++ - 将类对象指针打包成 char * 用于消息队列

c++ - 从终端在 Linux 机器上用 C++ 创建并包含头文件

java - 封装 - 在同一个类中使用 setter/getter ?

c++错误使用模板继承baseClass

c++ - 使用 enable_if 或类似的东西模板结构标签部分特化

loops - ansible 模板循环 jinja2 “我需要用 分隔行,但最后一个条目没有 ,

c++ - 可以放弃简单类的 getter 和 setter 吗?

c++ - 如何获得头文件中成员函数的正确代码覆盖率