TransWikia.com

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

Stack Overflow Asked by Ali Rojas on January 23, 2021

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.

One Answer

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

Correct answer by Dmitry Kuzminov on January 23, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP