Class Template with Template Class Friend: Delving into the Mechanics
Imagine constructing a binary tree (BT) class with an element class (BE) describing each node, resembling the following structure:
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 setup encounters a curious quirk. Attempting to declare the friend as template
This distinction stems from the concept of template shadowing. Template parameters cannot duplicate each other within the scope of nested templates. Consequently, different parameter names are indispensable for nested templates.
Consider the following constructs:
template<typename T> struct foo { template<typename U> friend class bar; };
Here, bar is declared as a friend to foo regardless of its own template arguments. All variations of bar, whether bar
In contrast, the following declaration:
template<typename T> struct foo { friend class bar<T>; };
Implies that bar is only a friend to foo when bar's template argument aligns with foo's. Only bar
Therefore, in your particular scenario, adopting the form friend class bar
The above is the detailed content of Why Do I Need a Separate Parameter for a Friend Template Class Inside a Class Template?. For more information, please follow other related articles on the PHP Chinese website!