Implementing multiple interfaces in 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;
};
现在,我想通过相同的层次结构实现这些接口,即基类 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.
请帮忙.提前致谢.
推荐答案
您可以使用单独的模板来实现每个单独的接口,然后将这些模板链接起来以像构建块一样构造派生对象.这个方法也被古老的 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++实现多个接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用c++实现多个接口
基础教程推荐
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01