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