Is it possible to prevent multiple inheritance of specific base classes at compile time?

前端 未结 2 937
粉色の甜心
粉色の甜心 2021-02-15 15:50

What I am looking to do is develop two different base classes which should not be inherited together in the one derived class. Is there any way I can enforce this at compile tim

2条回答
  •  北恋
    北恋 (楼主)
    2021-02-15 16:46

    You are setting up some kind of coupling between Base1 and Base2 in that they cannot both be derived from.

    You could make them both derive from Base0 in which case if you derive from Base1 and Base2 you would get the multiple inheritance diamond so you would get a compiler error assuming you do not use virtual inheritance and you do not resolve the duplication.

    That might solve your problem but I question why you are trying to do this.

    (Base0 should not be a totally empty class as there has to be something there ambiguous to cause the compiler to complain. And of course you could resolve it so it won't totally prevent you deriving from both, just that it will generate the required compiler "error" if you do it by mistake).

    An example might be:

    class Base0 
    { 
      protected: 
        virtual ~Base0(){};
        virtual void abstractMethod() const = 0;
    };
    
    class Base1 : public Base0
    { 
       protected:
         virtual void abstractMethod() const;
    
       // rest of Base1
    };
    
    class Base2 : public Base0
    { 
       protected:
         virtual void abstractMethod() const;
    
       // rest of Base1
    };
    
    class Derived : public Base1, public Base2
    {  
      // if I don't resolve abstractMethod it is ambiguous and the compiler will let me know
    };
    

提交回复
热议问题