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++实现多个接口


基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01