用c++实现多个接口

2021-12-12 00:00:00 oop 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> >]

相关文章