AleC
AleC

Reputation: 699

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;
}

Upvotes: 12

Views: 3425

Answers (2)

CashCow
CashCow

Reputation: 31445

It is not making the class a friend of itself, it is making all classes of that template a friend to all others. So A<Foo> is a friend of A<Bar> which is a different class.

I am surprised the syntax is as you print it and not template<typename U> friend class A<U>; but that is what it actually means.

Upvotes: 5

rashmatash
rashmatash

Reputation: 1819

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.

Upvotes: 25

Related Questions