简体   繁体   English

C ++防止某个类的派生类对两个类进行多重继承

[英]C++ Prevent multiple inheritance of two classes by the derived classes of a certain class

Kind of a verbose title, but here goes: 标题很冗长,但这里有:

I have a situation where I want to prevent two classes from being derived by the same class or any class of a family. 我有一种情况,我想防止两个类别由同一个类别或家庭的任何类别派生。 In code: 在代码中:

    class A;
    class B;

    class C: public A; //Yes.
    class D: public B; //Yes.

    class E: public A, public B; //Yes.
    class F: public C, public B; //Yes.

    class G: public A /*Disallow inheritance of B at this point somehow*/;
    class H: public G, public B; //Error at this point...

    class I;
    class J: public G, public I; //...but not at this point.

It's a situation where the private members of A and B are to remain private from any derived classes, and friendship would ruin that design. 在这种情况下,A和B的私有成员将对任何派生类保持私有,而友谊将破坏该设计。 How would I be able to do this? 我将如何做到这一点?

Without really looking deeper, it looks like a typical problem that's used to be solved using static (compile time resolved) polymorphism. 不用更深入地了解,它看起来像是一个典型的问题,以前是使用静态(已解决编译时间)多态性来解决的。 The basic approach for such frameworks is the CRTP meta programming pattern (simply because you introduce a strong policy for your inheriting class in how your parent/base classes can be used or combined). 这种框架的基本方法是CRTP元编程模式(这是因为您为继承类引入了一种强有力的策略来决定如何使用或组合父/基类)。

Have a look at how to provide 看看如何提供

  • type traits (there are some libs available to support this before C++11 stdandard compliance) 类型特征 (在符合C ++ 11标准之前,有一些库可用于支持此功能)
  • concept checks (several libs support this, eg boost::concept_check ) 概念检查(几个库支持此检查,例如boost::concept_check
  • SFINAE and/or explicit (compile time) error conditions SFINAE和/或显式(编译时)错误条件

You might consider various discrete client helper (API) classes to aggregate interface implementations for your final classes; 您可能会考虑使用各种离散的客户端帮助程序(API)类来汇总最终类的接口实现。 this refers to hiding certain implementations in compilation units and eventually necessary factories for creation of concrete instances. 这是指将某些实现隐藏在编译单元中,并最终隐藏在创建具体实例所需的工厂中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM