Template Style

I recently came across a piece of C ++ code where the class became a friend to myself. Since I read in various forums, the class is already a friend to myself. Therefore, I was wondering if there was any specific reason why a person would like to make a familiar class clearly.

Another question: what is the reason to make the class your friend?

Perhaps someone with more experience can clarify this topic.

Here is a sample code to illustrate my question:

template < typename T> class Foo: public T { protected: template < typename U> friend class Foo; } 
+6
source share
3 answers

It makes no sense to make the class a friend to yourself, except that it is a template class. For example, the following code makes sense:

 template <class T> class A { template<class U> friend class A; } 

An STL example is std::_Ptr_base , which is the base class for std::shared_ptr and std::weak_ptr .

+16
source

This does not make the class a friend; it makes all the classes of this template a friend to everyone else. So A<Foo> is a friend of A<Bar> , which is another class.

I am surprised at the syntax since you are typing it, not template<typename U> friend class A<U>; but that’s what it really means.

+2
source

No reason. The C ++ standard does not make it illegal, but creating your own friend of a class does not change anything, since the class already has full access to itself.

0
source

Source: https://habr.com/ru/post/973483/


All Articles