Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template class friendship

I recently came across a c++ piece of code where a class is made friend to itself. As I have read on different forums a class is already a friend to itself. So I was wondering if there is a specific reason why one would want to make a class friend to itself explicitly.

Another question would be, what's the reason in making a class a friend of itself?

Maybe someone with a lot of experience can clarify this topic.

Here is the code example, to illustrate my question:

template < typename T>
class Foo: public T
{
protected:
   template < typename U>
   friend class Foo;
}
like image 697
AlexandraC Avatar asked Aug 07 '14 12:08

AlexandraC


1 Answers

There's no point indeed to make a class a friend to itself, except if 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 the std::_Ptr_base which is the base class for std::shared_ptr and std::weak_ptr.

like image 190
rashmatash Avatar answered Sep 20 '22 12:09

rashmatash