Prevent inheritance of two classes from a base class with the same template arguments

I have a class that is supposedly the base class:

template<int ID> class BaseClass { ... }; 

How can I make a compile-time error if two classes try to inherit this base class using the same ID value. That is - this code should work:

 class A : BaseClass<1> { ... } class B : BaseClass<2> { ... } 

But this code makes a mistake:

 class A : BaseClass<1> { ... } class B : BaseClass<1> { ... } 

How can this be achieved? Does BOOST_STATIC_ASSERT help?

+6
c ++ inheritance boost assert templates
source share
3 answers

I think that this is impossible.

If this were possible, then we can make the compiler generate an error for the following code, which is conceptually equivalent to your code.

 struct Base {}; struct OtherBase {}; struct A : Base {}; //Base is used here! struct B : Base {}; // error - used base class. please use some other base! struct C : OtherBase {}; // ok - unused based! 
+1
source share

Just guess, but if you want to generate unique type identifiers, you can check this and this question.

+1
source share

I cannot think of any possible solution at compile time using C ++.

I can think of a possible solution at startup (initializing the library), but it will be limited.

 class A: public Base<A,1> {}; 

We have Base register the correspondence between id 1 and class typeid(A) during library initialization. If id exists and the classes do not agree, stop running.

However, there is one caveat:

 class A: public Base<A,1> {}; class C: public A {}; class D: public A {}; 

Nothing prevents classes originating from A from colliding.

I can offer static analysis: pick up the C ++ parser and program the binding before commit, which will check the modified files and see if they collide.

0
source share

All Articles