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++实现多个接口
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
