开发者

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 s开发者_运维问答uppose to cause an error:

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

How can one achieve this? Does BOOST_STATIC_ASSERT help?


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!


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


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

I can think of a possible solution at launch-time (library initialization), but it would be limited.

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

We have Base register the correspondence between the id 1 and the class typeid(A) during the library initialization. If an id exists and the classes disagree, then stop the launch.

There is one caveat however:

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

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

Nothing prevents classes deriving from A to clash.

I can suggest static analysis: pick up a C++ parser and program a pre-commit hook that will check the modified files and see if they introduce a clash.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜