Restrict inheritance to desired number of classes at compile-time

前端 未结 4 1636
野趣味
野趣味 2021-01-01 06:55

We have a restriction that a class cannot act as a base-class for more than 7 classes. Is there a way to enforce the above rule at compile-time?

I am aware of Andre

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-01 07:25

    I'm tired as crap, can barely keep my eyes open, so there's probably a more elegant way to do this, and I'm certainly not endorsing the bizarre idea that a Base should have at most seven subclasses.

    // create a template class without a body, so all uses of it fail
    template < typename D, typename B> class AllowedInheritance;
    
    
    class Base {};
    class Derived; // forward declaration
    
    // but allow Derived, Base by explicit specialization 
    
    template<> class AllowedInheritance< Derived, Base> {};
    
    // privately inherit Derived from that explicit specialization    
    class Derived : public Base, private AllowedInheritance {};
    
    
    // Do the same with class Compiler Error
    // it has no explicit specialization, so it causes a compiler error
    class CompileError: public Base, 
         private AllowedInheritance { };
    
    //error: invalid use of incomplete type 
    //‘struct AllowedInheritance’
    
    
    int main() {
    
       Base b;
       Derived d;
       return 0;
    }
    

    Comment from jon.h:

    How does this stop for instance: class Fail : public Base { }; ? \

    It doesn't. But then neither did the OP's original example.

    To the OP: your revision of my answer is pretty much a straight application of Coplien's "Curiously recurring template pattern"]

    I'd considered that as well, but the problem with that there's no inheritance relationship between a derived1 : pubic base and a derived2 : pubic base, because base and base are two completely unrelated classes.

    If your only concern is inheritance of implementation, this is no problem, but if you want inheritance of interface, your solution breaks that.

    I think there is a way to get both inheritance and a cleaner syntax; as I mentioned I was pretty tired when I wrote my solution. If nothing else, by making RealBase a base class of Base in your example is a quick fix.

    There are probably a number of ways to clean this up. But I want to emphasize that I agree with markh44: even though my solution is cleaner, we're still cluttering the code in support of a rule that makes little sense. Just because this can be done, doesn't mean it should be.

    If the base class in question is ten years old and too fragile to be inherited from, the real answer is to fix it.

提交回复
热议问题