c++ - How to merge two classes with much the same code but operating on different structures -
i trying improve existing c++ code removing duplicated code, cannot come convincing way of doing it. insight more experienced c++ colleagues appreciated.
so have 2 structure definitions on have no control:
struct struct_1 { ... other_s * s1; other_s * s2; other_s * s3; ... //other fields }; struct struct_2 { ... other_s * s1; other_s * s2; other_s * s3; ... //other fields, different struct_1, not important };
and code want improve. have 2 identical classes, operate in same way on structure fields of same names, fields come different structures. classes not operate on structure fields present in 1 structure. here goes (simplification):
class class_1 { struct_1 * s; class_1(){ s = new struct_1(); //the practical difference ... } void method() { ... //this simplification, in reality code more complex //however same in class_2 inner_data += s->s1; inner_data += s->s2; inner_data += s->s3; ... } //other methods }; class class_2 { struct_2 * s; class_2(){ s = new struct_2(); //the practical difference ... } void method() { ... //this simplification, in reality code more complex //however same in class_1 inner_data += s->s1; inner_data += s->s2; inner_data += s->s3; ... } //other methods };
i have spent time trying rework ended nowhere. approach use 1 class class_1, couldn't avoid problems accessing struct_1 , struct_2 without multiple if's scattered around. thank help!
c++ has templates this:
template<typename t> class myclass { t* s; myclass(){ s = new t(); //the practical difference ... } void method() { ... //this simplification, in reality code more complex //however same in class_2 inner_data += s->s1; inner_data += s->s2; inner_data += s->s3; ... } //other methods };
now can use classes as:
myclass<struct_1> a;
and
myclass<struct_2> b;
and compiler generate definitions these classes based on template.
don't forget deallocate memory in destructor!
Comments
Post a Comment