Friend all classes that inherit from class

This is more of an intellectual curiosity than a real problem. I was wondering if there is a way in C ++ to do the following: let Abe a class. I want to create a Bfriend class with all classes inheriting from A.

Before you say this: I obviously know that friendship is not inherited. I would like to make an expression template friend, possibly using SFINAE, to a friend Bwith each class Cto Cinherit from A.

Is this possible? I tried to start with the simplest case: can you make a cool friend with all the other classes? Obviously, I know that this makes no sense, you can just make something publicly available, but maybe from this starting point you can improve to select only those classes that inherit from A.

+4
source share
1 answer

A workaround should be to use an inherited access key.

// 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.
};
+1
source

Source: https://habr.com/ru/post/1680150/


All Articles