2012-07-28 36 views
0

有时候我发现自己写很简单的包装,其中包装方法直接对应于改编类的一个方法,即:简化包装创作

class ToBeAdapted 
{ 
    public: 
    void a(); 
    void b(int arg); 
}; 

class Wrapper 
{ 
    public: 
    void newA() 
    { 
     _adapted.a(); 
    } 

    void newB(int arg) 
    { 
     _adapted.b(arg); 
    } 

    private: 
    ToBeAdapted _adapted; 
}; 

可以这样(也许使用的模板魔法和/或黑暗的预处理器仪式?)有所概括,只是为了节省写入时间,并且以后更容易切换包装器接口?

像这样的事情会很酷:

wrap_around<ToBeAdapted>(ToBeAdapted::a, newA, ToBeAdapted::b,newB) Wrapper; //Creates the same wrapper class as specified above. 

回答

2

考虑使用私有继承:

class Wrapper : ToBeAdapted 
{ 
    public: 
    void newA() { a(); } 
    void newB(int arg) { b(arg); } 
};