Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent two classes from inheriting from a base class with same template arguments

I have a class that is suppose to be a base class:

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

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

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

But this code is suppose to cause an error:

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

How can one achieve this? Does BOOST_STATIC_ASSERT help?

like image 470
Bartłomiej Siwek Avatar asked Mar 14 '11 12:03

Bartłomiej Siwek


2 Answers

I think that is impossible.

If it were possible, then we can make compiler to generate error for the following code as well, 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!
like image 182
Nawaz Avatar answered Oct 24 '22 02:10

Nawaz


Just guessing, but in case you want to generate unique type ids, you may want to check out this and this question.

like image 40
Björn Pollex Avatar answered Oct 24 '22 02:10

Björn Pollex