2015-08-27 66 views
0

有2个类,大多数代码是相同的。使用模板来代替预处理?

template<typename T> 
class A1 { 
f1(){common code... do_with(_m) ... common code} 
f2(); 
fn(); 
T _m; 
}; 

template<typename T> 
class A2 { 
f1(){common code... do_with(_m, _b) ... common code} 
f2(); 
fn(); 
B _b; 
std::atomic<T*> _m; 
}; 

因为95%的代码是一样的,我想使那些2级为一个,但我不能使用预处理因为他们都将在一个项目中使用。因为这两个类是模板,所以我不能使用“模板方法”设计模式将相同的代码提取到基类中,并将一些私有虚函数留给派生类来覆盖。

是否有可能避免代码重复?例如:

A<T, type_a1> a1; 
A<T, type_a2> a2; 

我已经考虑模板专业化,但它不能支持“提取码的共同部分”,一个专门的类必须重写整体功能

回答

0

方法1

template <typename T> 
void common_f1_pre(T& t) { ... } 

template <typename T> 
void common_f1_post(T& t) { ... } 

在A1:

f1(){common_f1_pre(_m); do_with(_m); common_f1_post(_m); } 

在A2:

f1(){common_f1_pre(_m); do_with(_m, _b); common_f1_post(_m); } 

方法2

template <typename A> 
void common_f1(A& a) 
{ 
    // Common to A1 and A2 ... } 

    a.f1_core(); 

    // Common to A1 and A2 
} 

在A1:

f1(){f1_common(*this);} 
f1_core() {do_with(_m);} 

在A2:

f1(){f1_common(*this);} 
f1_core() {do_with(_m, _b);}