在编译时将继承限制为所需数量的类

Abh*_*hay 3 c++ inheritance friend

我们有一个限制,即一个类不能作为超过7个类的基类.有没有办法在编译时强制执行上述规则?

我知道Andrew Koenig的Usable_Lock技术可以防止类被继承,但只有当我们尝试实例化类时它才会失败.在推导自己时不能这样做吗?

允许基类知道谁是其子女.所以我想我们可以声明友好类的组合并封装它们来强制执行此规则.假设我们尝试这样的事情

class AA {
   friend class BB;
   private:
      AA() {}
      ~AA() {}
};

class BB : public AA {

};

class CC : public AA 
{};
Run Code Online (Sandbox Code Playgroud)

类CC的推导将生成编译器警告abt无法访问的dtor.然后,我们可以使用编译器调整(例如将所有警告标记为错误)将这些警告标记为错误,但我不想依赖这些技术.

另一种方式,但对我来说看起来很笨拙是: -

class B;

class InheritanceRule{
    class A {
    public:
        A() {}
        ~A() {}
    };
    friend class B;
};

class B {
public:
    class C : public InheritanceRule::A
    {};
};


class D : public InheritanceRule::A{};
Run Code Online (Sandbox Code Playgroud)

D类的派生将被标记为编译器错误,这意味着要派生的所有类都应该在B类中派生.这将允许至少检查从A类派生的类的数量,但不会阻止任何人添加更多.

这里有谁有办法吗?如果基类不需要知道谁是它的孩子,那就更好了.

注意:充当基类的类本身可以实例化(它不是抽象的).

提前致谢,

编辑1:根据jon.h的评论,略有修改

// create a template class without a body, so all uses of it fail
template < typename D> 
class AllowedInheritance;

class Derived; // forward declaration
// but allow Derived by explicit specialization 
template<> 
class AllowedInheritance< Derived> {};

template<class T>
class Base : private AllowedInheritance<T> {};

// privately inherit Derived from that explicit specialization    
class Derived : public Base<Derived> {};

// Do the same with class Fail Error
// it has no explicit specialization, so it causes a compiler error
class Fail : public Base<Fail> {}; // this is error

int main()
{   
   Derived d;

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

mar*_*h44 5

对不起,我不知道如何使用编译器强制执行任何此类限制.

就个人而言,我不打算试图强制规则进入代码本身 - 你使用与代码正在做的事情无关的东西使代码混乱 - 这不是干净的代码.

我试图让这条规则放松,而不是跳过篮球.相反,它应该是一个可以在必要时与团队中的其他人一致的指南.

当然,我不知道你究竟在做什么,所以规则可能是合适的,但总的来说可能不是.

任何编程"规则",你必须永远不要做x或你必须总是做y几乎总是错的!注意那里的"差不多"这个词.

有时您可能需要 7个以上的派生类 - 那么您会怎么做?跳过更多的箍.还有,为什么7?为什么不是6或8?它只是如此随意 - 这是一个糟糕的统治的另一个迹象.

如果你必须这样做,正如JP所说,静态分析可能是更好的方法.