Matteo Monti
Matteo Monti

Reputation: 8950

Friend all classes that inherit from a class

This is more of an intellectual curiosity than an actual problem. I was wondering if there is a way, in C++, to do the following: let A be a class. I want to make a class B friend with all the classes that inherit from A.

Before you say it: I obviously know that friendship is not inherited. What I would like to do is to make a template friend statement, maybe using SFINAE, to friend B with each and every class C so that C inherits from A.

Is such a thing even possible? I tried to start from the simplest case: can you make a class friend with all other classes? Obviously I know this doesn't make any sense, one could just make things public, but maybe from this starting point things can be perfected to select only those classes that inherit from A.

Upvotes: 5

Views: 105

Answers (1)

Jarod42
Jarod42

Reputation: 217448

A work-around would be to use an inherited "key" access.

// Class to give access to some A members
class KeyA
{
private:
    friend class B; // Give access to base class to create the key
    KeyA() = default;
};


class A
{
public: // public, but requires a key to be able to call the method
    static void Foo(KeyA /*, Args... */) {}
    static void Bar(KeyA /*, Args... */) {}
};


class B
{
protected:
    static KeyA GetKey() { return KeyA{}; } // Provide the key to its whole inheritance
};

class D : public B
{
public:
    void Foo() { A::Foo(GetKey()); } // Use A member with the key.
};

Upvotes: 1

Related Questions