Home > Backend Development > C++ > Why Do I Need a Separate Parameter for a Friend Template Class Inside a Class Template?

Why Do I Need a Separate Parameter for a Friend Template Class Inside a Class Template?

Barbara Streisand
Release: 2024-11-17 18:40:02
Original
270 people have browsed it

Why Do I Need a Separate Parameter for a Friend Template Class Inside a Class Template?

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:
    ...
};
Copy after login

This setup encounters a curious quirk. Attempting to declare the friend as template friend class BT; fails, necessitating the usage of a separate parameter U (or any non-T parameter).

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;
};
Copy after login

Here, bar is declared as a friend to foo regardless of its own template arguments. All variations of bar, whether bar, bar, bar, or others, become friends to any instantiation of foo.

In contrast, the following declaration:

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

Implies that bar is only a friend to foo when bar's template argument aligns with foo's. Only bar would be considered a friend to foo.

Therefore, in your particular scenario, adopting the form friend class bar; should effectively establish the desired friend relationship between BE and BT.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template