"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does a Templated Class Need to Declare a Friend Templated Class with a Different Template Parameter?

Why Does a Templated Class Need to Declare a Friend Templated Class with a Different Template Parameter?

Published on 2024-11-13
Browse:327

Why Does a Templated Class Need to Declare a Friend Templated Class with a Different Template Parameter?

Template Class with Friend Templated Class: Deciphering the Mechanics

In this scenario, you're defining a binary tree class template (BT) and a class template (BE) that represents an element of the tree. You encounter a peculiar requirement to declare the friend template as BT instead of BT. An investigation into this behavior leads to a thorough understanding of class templates and friend relationships.

Nested Templates and Shadowing

Initially, you attempt to declare the friend template as template friend class BT;. However, this is prohibited because the template parameters of nested templates cannot have the same name. Nested templates must utilize distinct template parameter names.

Defining Friend Relationships

When you declare template friend class BT;, you establish a friend relationship between BT and BE, irrespective of the template arguments of BT. This means that any instantiation of BT can access the private members of any instantiation of BE.

If you wish to restrict the friend relationship to only those instantiations of BT that utilize the same template argument as BE, you should declare the friend as follows:

template friend class bar;

In your specific case, declaring friend class bar; within the BE class should suffice.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3