用c++实现多个接口

Implementing multiple interfaces in c++(用c++实现多个接口)
本文介绍了用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;
};

现在,我想通过相同的层次结构实现这些接口,即基类 AImplBImplCImpl 但我是不确定如何从它们对应的接口派生它们.

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.

请帮忙.提前致谢.

推荐答案

您可以使用单独的模板来实现每个单独的接口,然后将这些模板链接起来以像构建块一样构造派生对象.这个方法也被古老的 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
", __PRETTY_FUNCTION__); }
};

template<class I>
struct BImpl : I
{
    void testB() { printf("%s
", __PRETTY_FUNCTION__); }
};

template<class I>
struct CImpl : I
{
    void testC() { printf("%s
", __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++实现多个接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Bring window to front -gt; raise(),show(),activateWindow() don’t work(把窗户放在前面 -raise(),show(),activateWindow() 不起作用)
How to get a list video capture devices NAMES (web cameras) using Qt (crossplatform)? (C++)(如何使用 Qt(跨平台)获取列表视频捕获设备名称(网络摄像机)?(C++))
How to compile Qt as static(如何将 Qt 编译为静态)
C++ over Qt : Controlling transparency of Labels and Buttons(C++ over Qt:控制标签和按钮的透明度)
How to know when a new USB storage device is connected in Qt?(Qt如何知道新的USB存储设备何时连接?)
What is an event loop in Qt?(Qt 中的事件循环是什么?)