从一个类虚拟强制派生 [英] Force deriving from a class virtually

查看:133
本文介绍了从一个类虚拟强制派生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在我们的项目中有一个特殊的接口框架,部分需求是代表接口的类只能用作虚拟基类,而不能用作非虚拟基类。有没有办法在代码中强制执行?

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:


  1. class Base 设为 final (c ++ 11);即 class Base final {...

  2. 编译代码,它将为其所有
    派生类

  3. 转到并检查每个派生类,并将继承作为
    virtual

  4. 删除 final 关键字并成功编译代码

  1. Make class Base as final (c++11); i.e. class Base final { ...
  2. Compile the code, it will generate compiler error for all its derived classes
  3. Go and check every derived class and make the inheritance as virtual
  4. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆