从一个类虚拟强制派生 [英] Force deriving from a class virtually
问题描述
我们在我们的项目中有一个特殊的接口框架,部分需求是代表接口的类只能用作虚拟基类,而不能用作非虚拟基类。有没有办法在代码中强制执行?
We have a special framework for interfaces in our project, and part of the requirements is that classes which represent an interface may only be used as virtual base classes, not as non-virtual ones. Is there a way to enforce this in code? That is, produce a compilation error if the class is derived from non-virtually.
我可以访问VS 2010实现的C ++ 11:这意味着 static_assert
, enable_if
和< type_traits>
p>
I have access to C++11 as implemented by VS 2010: this means static_assert
, enable_if
and <type_traits>
are available.
推荐答案
IMO,没有干净的,与平台无关的解决方案可用于此问题。
IMO, there is no clean and platform independent solution available to this problem.
最好的办法是手动去改变每个继承到 virtual
继承。
要实现这一点,识别接口的派生类(例如 class Base
)很容易(!)。以下步骤可以执行:
The best way is to manually go and change each and every inheritance to virtual
inheritance.
To accomplish that, identifying the derived classes of your interface (say class Base
) is easy(!). Below steps can be followed for that:
- 将
class Base
设为final
(c ++ 11);即class Base final {...
- 编译代码,它将为其所有
派生类 - 转到并检查每个派生类,并将继承作为
virtual
- 删除
final
关键字并成功编译代码
- Make
class Base
asfinal
(c++11); i.e.class Base final { ...
- Compile the code, it will generate compiler error for all its derived classes
- Go and check every derived class and make the inheritance as
virtual
- Remove the
final
keyword and compile the code successfully
)必须定期进行,每当你想做这样的健全检查。
This process (unfortunately) has to be followed periodically, whenever you want to do such sanity checking.
这篇关于从一个类虚拟强制派生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!