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

假设我正在为二叉树 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:
...
};

这似乎是有效的,但是我对下面发生了什么有疑问。

我本来想声明这个朋友是

template<class T> friend class BT;

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

关于模板和好友的 IBM 页面有不同类型的函数好友关系的示例,但没有类(并且猜测语法还没有在解决方案中趋于一致)。我更愿意了解如何获得正确的规格类型的朋友关系,我希望定义。

107738 次浏览
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;
};

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

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>.


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

In my case this solution works correctly:

template <typename T>
class DerivedClass1 : public BaseClass1 {
template<class T> friend class DerivedClass2;
private:
int a;
};


template <typename T>
class DerivedClass2 : public BaseClass1 {
void method() { this->i;}
};

I hope it will be helpful.

In order to befriend another same-type struct:

#include <iostream>


template<typename T_>
struct Foo
{
// Without this next line source.value_ later would be inaccessible.
template<typename> friend struct Foo;


Foo(T_ value) : value_(value) {}


template <typename AltT>
void display(AltT &&source) const
{
std::cout << "My value is " << value_ << " and my friend's value is " << source.value_ << ".\n";
}


protected:
T_ value_;
};


int main()
{
Foo<int> foo1(5);
Foo<std::string> foo2("banana");


foo1.display(foo2);


return 0;
}

With the output as follows:

My value is 5 and my friend's value is banana.

In template<typename> friend struct Foo; you shouldn't write T after typename/class otherwise it will cause a template param shadowing error.

It's not necessary to name the parameters so you get fewer points of failure if refactoring:

     template <typename _KeyT, typename _ValueT> class hash_map_iterator{
template <typename, typename, int> friend class hash_map;
...

The best way to make a template class a friend of a template class is the following:

#include <iostream>
using namespace std;


template<typename T>
class B;


template<typename T>
class A
{
friend class B<T>;
private:
int height;
public:
A()//constructor
A(T val) //overloaded constructor


};


template<typename T>
class B
{
private:
...
public:
B()//constructor
B(T val) //overloaded constructor
};