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

流过昼夜 提交于 2019-12-20 01:06:58

问题


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 : public B, public C
{
    BOOST_STATIC_ASSERT((is_base_of_once<A,D>::value))
};

回答1:


The following should work:

BOOST_STATIC_ASSERT(((A*)(D*)0 == 0)) 

If A exists twice, this should rise an ambiguity error, while otherwise the test will always succeed (because it compares two null pointers).




回答2:


When I try to derive a class twice as you have here it does not even compile. (duplicate base type)




回答3:


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<A,B>::value && is_base_of<A,C>::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
};


来源:https://stackoverflow.com/questions/8851583/is-there-a-way-to-prevent-a-class-from-being-derived-from-twice-using-a-static-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!