C++: Can a Template be friend of a Class?
Asked Answered
K

1

7

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.

Kelcy answered 5/8, 2020 at 1:1 Comment(3)
What sort of template is B? Can you show some example usage?Guesthouse
"A is an small and simple class with a lot of friends who manipulate its attributes". Maybe all its members should be public?Guesthouse
@cigien: all the friend are well-know an confiable classes, so inside them A's attributes are safe. But I don't know about other applications who use my entire system.Kelcy
L
8

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

Luby answered 5/8, 2020 at 1:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.