lundi 5 avril 2021

2 C++ classes with same functionality but different variable names - which pattern to use?

I have 2 C++ classes which have the same variable types and need to perform exactly the same operations on these variables. However, the variable and function names of these 2 classes are different as they mean different things in their respective classes.

How can I achieve this without code duplication? Does inheritance or templates help here?

Here's a stripped down example.

class A
{
    private:
       float m;
       float n;

    public:
       float foo() {return m + n};
};

class B
{
    private:
       float p;
       float q;

    public:
       float bar() {return p + q};
};

In my case, the operations and variables are more complicated than the above toy example. The only difference between the 2 classes are the variable and function names. The rest is identical. How can I refactor this in C++?

Aucun commentaire:

Enregistrer un commentaire