mercredi 26 août 2015

use template to instead preprocessor?

There are 2 classes, most code is same.

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;
};

Because 95% code is same, I want to make those 2 class into one, but I can not use preprocessor due to both of them will be used in one project. And because these 2 class is template, so I can not use "template method" design pattern to extract same code into a base class and leave some private virtual function to derived class to override.

Is it possible to avoid code duplication? For example:

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

I have considered template specialization, but it can not support "extract the common part of code", a specialized class have to rewrite whole function

Aucun commentaire:

Enregistrer un commentaire