我的界面层次结构如下:
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; };现在,我想通过相同的层次结构实现这些接口,即Base类 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.
请帮助。 提前感谢。
Please help. Thanks in advance.
推荐答案您可以使用单独的模板实现每个个性化界面,然后链接模板派生对象好像来自构建块。这个方法也被可靠的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\n", __PRETTY_FUNCTION__); } }; template<class I> struct BImpl : I { void testB() { printf("%s\n", __PRETTY_FUNCTION__); } }; template<class I> struct CImpl : I { void testC() { printf("%s\n", __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 ++中实现多个接口
发布评论