我正在开发一个API,其中类A派生为类B。
如果 API 用户希望在应用程序级别扩展 A 类和 B 类的功能,那么就会出现问题。
假设应用程序用户提出类 AX 扩展类 A,类 BX 扩展类 B。在这种情况下,用户不会获得类 BX 的预期行为,因为类 B 的基类是类 A 而不是类 AX。
思想:应用程序用户可以同时使用 B 类和 AX 类扩展类 BX,但在这种情况下,我认为会有已知的菱形行为。
我想知道,解决此问题的任何标准方法。
从模板参数继承的类也是一种选择。 伪代码:
class A;
template<typename WhichA>
class B : public WhichA;
class AX : public A;
class BX : public B<AX>;
你的问题有点模糊。无论如何,我建议您阅读C++常见问题解答25和问题25.5。问题25.5和25.6讨论了一些备选办法。
。但在这种情况下,我认为会有已知的钻石行为
那么问题出在哪里呢? virtual
继承是为了解析这种菱形图案。
如果A
的孩子实际上是继承的,那么我认为没有任何问题,除非改变设计。
class InterfaceA;
class InterfaceB;
class A : public InterfaceA;
template<class AType>
class B_Template : public InterfaceB, public AType;
// Below is same as class B in example
// Users can use B as if it was class B
typedef B_Template<A> B;
// User can extend A
class AX : A;
// User can extend B any way they want (you can't police this)
// but the way you wanted in the question was:
class BX : B_Template<AX>; // Inherits of the extended AX
这解决了您的问题,但正如评论中指出的那样,您应该考虑依赖注入而不是继承。
此外,接口类并不是真正需要的,但它可以清楚地表明基类上的协定是什么 - 即模板参数 AType 必须满足 InterfaceA。