2013-02-15 54 views
4

我有一个这样的接口(除了很多很多在真实库的代码比这更长)如何避免重复代码的静态多态性

struct IFoo 
{ 
    virtual void onA(A& a) = 0; 
    virtual void onB(A& a) = 0; 
    virtual void onC(A& a) = 0; 
}; 

,这是常见的对我实施的IFoo不同的听众。所以现在

template <class T> 
struct IFooHelper { 
    virtual void onA(A& a) { static_cast<T*>(this)->onGeneric(a); } 
    virtual void onB(B& b) { static_cast<T*>(this)->onGeneric(b); } 
    virtual void onC(C& c) { static_cast<T*>(this)->onGeneric(c); } 
}; 

,当我在听众有很多共同的行为,而不是提供每一个IFoo功能的虚拟覆盖,I:正因为如此,我设计了一个辅助类,像这样的可以这样做:

struct Fox : public IFooHelper<Fox> 
{ 
    template <class T> void onGeneric(T& t) { //do something general } 
    void onD(D& d) { //special behavior only for a type D } 
}; 

这飞驰的效果很好,但现在我实现了,我想一些常见的行为,然后再更新计数器,也就是说,其呼叫类型,这是一个倾听者。换句话说,假设我只有为上述各类A,B,C,我的听众是:

struct Ugly : public IFooHelper<Ugly> 
{ 
    void onA(A& a) { //8 lines of common code; //update some counter for type A objs; } 
    void onB(B& b) { //8 lines of common code; //update some counter for type B objs; } 
    void onC(C& c) { //8 lines of common code; //update some counter for type C objs; } 
}; 

在这里,调用必须非常快(所以没有查找)和理想,我将能够利用IFooHelper将常见行为提升到模板方法中,然后以某种方式仍然能够区分类型。我想像一个模板专门的结构与偏移到一个静态缺陷字符*数组..或与价值本身是char *取决于T ..有没有更好的办法?

+0

Hope [this](http://en.wikipedia.org/wiki/Template_method_pattern)有帮助。 – 2013-02-15 02:10:07

+0

如何使用其他方法中内联的通用代码的单独方法? – wich 2013-02-15 02:26:11

+0

@wich,想到了这一点...目前我已经实现了一个带有静态偏移量的模板专用结构宏。 – 2013-02-15 02:58:29

回答

1

不知道如果我完全理解你在找什么,但我会给它一个镜头。作为第一步,可以这样考虑:

struct NotSoUgly : public IFooHelper<NotSoUgly> 
{ 
    void updateCounter(A& a) { //update some counter for type A objs; } 
    void updateCounter(B& b) { //update some counter for type B objs; } 
    void updateCounter(C& c) { //update some counter for type C objs; } 

    template <class T> void onGeneric(T& t) { 
     //8 lines of common code; 
     updateCounter(t); 
    } 
}; 

进一步的改善是可能的,如果你想向我们展示的updateCounter()方法的内容,我们可以拿出一个通用的实施,作为好,但没有看到代码,很难猜测。

+0

谢谢,鉴于目前的情况,这似乎是最好的。我将在几个小时内进行编辑,以显示我最终做了什么。 – 2013-02-21 17:00:15