朋友,从班级继承的所有课程

Friend all classes that inherit from a class

本文关键字:继承 朋友      更新时间:2023-10-16

这更像是一种智力上的好奇心,而不是实际问题。我想知道在C 中是否有办法进行以下操作:让A成为一类。我想与所有从A继承的类结合B朋友。

在您说之前:我显然知道友谊不是继承的。我想做的是使用和每个类CB进行template friend语句,也许使用Sfinae,以便CA继承。

这是可能的吗?我试图从最简单的情况开始:您可以与所有其他班级结交一堂朋友吗?显然,我知道这没有任何意义,一个人可以将事物公开,但是也许从这个起点可以完善事情,只能选择从A继承的类。

一个工作要解决的是使用继承的"键"访问。

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