Ali Rojas
Ali Rojas

Reputation: 639

C++: Can a Template be friend of a Class?

Is it possible to make friend of a class, all possible variants of a class-template?

Just to clarify, for example, something like this:

class A
{ friend template B; }    // syntactic error yeah

So any B<X> variant could manipulate any protected attribute of A.

A is an small and simple class with a lot of friends who manipulate its attributes. Just one of then need to be a template. I know that I can do this:

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

But so I would have to change my code in all the other friends and I would like to avoid it.

Upvotes: 7

Views: 765

Answers (1)

Dmitry Kuzminov
Dmitry Kuzminov

Reputation: 6584

You may define a friend template class like that:

class A{
    template<typename T>
    friend class B;
};

That would make every specialization of class B a friend of class A. I've had a similar question that had the opposite goal: to restrict some specializations: Friend template function instantiations that match parameter

Upvotes: 9

Related Questions