Home  >  Article  >  Backend Development  >  Why Use Different Template Parameters for Friend Classes in Nested Templates?

Why Use Different Template Parameters for Friend Classes in Nested Templates?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-14 20:50:02837browse

Why Use Different Template Parameters for Friend Classes in Nested Templates?

Friend Class Templates in Nested Templates

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; should suffice to establish the desired friendship relationship.

The above is the detailed content of Why Use Different Template Parameters for Friend Classes in Nested Templates?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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