Is there a way to prevent the class from being double-drawn from using the static attribute assert and type?

I understand this is a far-fetched example, but I need a compilation 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)) }; 
+4
source share
3 answers

The following should work:

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

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

+4
source

When I try to get a class twice like you are here, it doesn't even compile. (duplicated base type)

0
source

If you really want this, you will check both 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 classes inherited from almost A, so that only one instance remains 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 }; 
0
source

Source: https://habr.com/ru/post/1390840/


All Articles