在c ++中实现多个接口

编程入门 行业动态 更新时间:2024-10-27 02:30:41
本文介绍了在c ++中实现多个接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的界面层次结构如下:

I have the interface hierarchy as follows:

class A { public: void foo() = 0; }; class B: public A { public: void testB() = 0; }; class C: public A { public: void testC() = 0; };

现在,我想通过相同的层次结构实现这些接口,即Base类 AImpl , BImpl 和 CImpl ,但我不知道如何导出

Now, I want to implement these interfaces by the same hierarchy, that is a Base class AImpl, BImpl and CImpl but I am not sure how to derive them from their corresponding interfaces.

请帮助。 提前感谢。

Please help. Thanks in advance.

推荐答案

您可以使用单独的模板实现每个个性化界面,然后链接模板派生对象好像来自构建块。这个方法也被可靠的ATL库用于实现COM接口(对于我们这些人来说已经够旧了)。

You can implement each individial interface using a separate template and then chain the templates to construct the derived object as if from building blocks. This method was also used by venerable ATL library to implement COM interfaces (for those of us old enough).

注意,你不需要虚拟继承。

Note that you don't need virtual inheritance for that.

我略微修改了一个更复杂的派生的例子 C - > B - > A 以显示此方法如何轻松扩展:

I slightly modified you example for a more complex derivation C -> B -> A to show how this method scales easily:

#include <stdio.h> // Interfaces struct A { virtual void foo() = 0; }; struct B : A { virtual void testB() = 0; }; struct C : B { virtual void testC() = 0; }; // Implementations template<class I> struct AImpl : I { void foo() { printf("%s\n", __PRETTY_FUNCTION__); } }; template<class I> struct BImpl : I { void testB() { printf("%s\n", __PRETTY_FUNCTION__); } }; template<class I> struct CImpl : I { void testC() { printf("%s\n", __PRETTY_FUNCTION__); } }; // Usage int main() { // Compose derived objects from templates as from building blocks. AImpl<A> a; BImpl<AImpl<B> > b; CImpl<BImpl<AImpl<C> > > c; a.foo(); b.foo(); b.testB(); c.foo(); c.testB(); c.testC(); }

输出:

void AImpl<I>::foo() [with I = A] void AImpl<I>::foo() [with I = B] void BImpl<I>::testB() [with I = AImpl<B>] void AImpl<I>::foo() [with I = C] void BImpl<I>::testB() [with I = AImpl<C>] void CImpl<I>::testC() [with I = BImpl<AImpl<C> >]

更多推荐

在c ++中实现多个接口

本文发布于:2023-05-26 06:15:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/252271.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   接口

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!