如何合并两个具有相同代码但在不同结构上运行的类

you*_*uri 2 c++ refactoring design-patterns code-duplication

我试图通过删除重复的代码来改进现有的C++代码,但无法提出令人信服的方法.来自更有经验的C++同事的任何见解都非常感谢.

所以我有两个结构定义,我无法控制:

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 than struct_1, but not that important
};
Run Code Online (Sandbox Code Playgroud)

最后我要改进的代码.我有两个几乎相同的类,它们以相同的方式在相同名称的结构字段上操作,但字段来自不同的结构.这些类不对仅存在于一个结构中的结构字段进行操作.这里(简化):

class class_1
{
    struct_1 * s;

    class_1(){
        s = new struct_1(); //the only practical difference
        ...
    }

    void method()
    {
        ...

        //this is simplification, in reality the code is more complex
        //however the same as 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 only practical difference
        ...
    }

    void method()
    {
        ...

        //this is simplification, in reality the code is more complex
        //however the same as in class_1
        inner_data += s->s1;
        inner_data += s->s2;
        inner_data += s->s3; 
        ...
    }
    //other methods
};
Run Code Online (Sandbox Code Playgroud)

我花了一些时间尝试重做它,但结果无处可去.我的方法是只使用一个类class_1,但我无法避免访问struct_1和struct_2而没有多个if_散布的问题.谢谢您的帮助!

Nem*_*ric 5

C++有一个模板:

template<typename T>
class MyClass
{
    T* s;

    MyClass(){
        s = new T(); //the only practical difference
        ...
    }

    void method()
    {
        ...

        //this is simplification, in reality the code is more complex
        //however the same as in class_2
        inner_data += s->s1;
        inner_data += s->s2;
        inner_data += s->s3; 
        ...
    }
    //other methods
};
Run Code Online (Sandbox Code Playgroud)

现在您可以将您的类用作:

MyClass<struct_1> a;
Run Code Online (Sandbox Code Playgroud)

MyClass<struct_2> b;
Run Code Online (Sandbox Code Playgroud)

和编译器将根据您的模板为这些类生成定义.

不要忘记在析构函数中释放内存!