Consider the scenario of defining a class template for a binary tree (BT) and an element within the tree (BE). When declaring the friendship between these classes, why is it necessary to use a different template parameter for the friend class compared to the containing class?
In C++, template parameters cannot shadow each other. In the context of nested templates, the template parameters of the inner template must have different names than the template parameters of the outer template.
For example, in the following code:
template<class T> class BE { T *data; BE *l, *r; public: template<class U> friend class BT; };
The template parameter U of the friend class BT is used to differentiate it from the T template parameter of the BE class. This specifies that BT is a friend of BE regardless of BT's template arguments.
However, if you declare the friend class as follows:
template<class T> friend class BT;
This implies that any particular instantiation of BT is a friend to any particular instantiation of BE. To specify a more specific friendship, you can use the following syntax:
template<typename T> struct foo { friend class bar<T>; };
This indicates that bar is a friend of foo only when bar's template argument matches foo's template argument. In your case, using friend class bar
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!