c++ - How can I group the common code within two classes that have the exact same definitions but the type of one member variabl

admin2025-04-26  13

I have two classes: Motor_Distance and Motor_Displacement that both contain identical code, however the type of the member variable count and the return type of the accessor convToCount is the only difference.

In Motor_Displacement, count is a long since it can be both negative and positive.

In Motor_Distance, count is a unsigned long since it cannot be negative. Thus it is unsigned so i can store higher positive values of count

Here is the code:

constexpr double pi = 3.14159; 

class Motor_Distance{
    private:
        unsigned long count;
        float wheel_diameter;
        unsigned int pulses_per_revolution;
    
    public: 
        unsigned long convToCount(){ return count; }
        
        float convToMeters(){
            return  convToCount() * pi * wheel_diameter / pulses_per_revolution;
        }
};

class Motor_Displacement{
        long count;
        float wheel_diameter;
        unsigned int pulses_per_revolution;
    public:
 
        long convToCount(){ return count; }
  
        float convToMeters(){
            return  convToCount() * pi * wheel_diameter / pulses_per_revolution;
        }
};

int main(){
}

Since both classes contain repeated code, and I want to remove this repeated code. I could achieve this using a template base class as follows:

constexpr double pi = 3.14159; 

template<typename Travel_Type>
class Motor_Travel{
        Travel_Type count;
        float wheel_diameter;
        unsigned int pulses_per_revolution;
    public:
 
        Travel_Type convToCount(){ return count; }
  
        float convToMeters(){
            return  convToCount() * pi * wheel_diameter / pulses_per_revolution;
        }
};

class Motor_Distance : public Motor_Travel<unsigned long>{};
class Motor_Displacement : public Motor_Travel<long>{};

int main(){
}

I there a way I can do a similar thing (group/remove repeated code) without using templates?

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745658866a312619.html

最新回复(0)