Is there a way to prevent a class from being derived from twice using a static assert and type trait?

前端 未结 3 1802
北海茫月
北海茫月 2021-01-19 08:10

I realize this is a contrived example, but I want a compile check to prevent this...

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

class D : pub         


        
3条回答
  •  时光说笑
    2021-01-19 08:38

    If you really want to, you an test both your base classes:

    class A {};
    class B : public A {};
    class C : public A {};
    
    class D : public B, public C
    {
        static_assert(!(is_base_of::value && is_base_of::value),
                       "Invalid inheritance!");
    };
    

    Otherwise you can make the classes inherit virtually from A, so that there will still only be one instance of it in the derived class:

    class A {};
    class B : public virtual A {};
    class C : public virtual A {};
    
    class D : public B, public C
    {
        // only one A here
    };
    

提交回复
热议问题