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

I have two classes: Motor_Distance and Motor_Displacement that both contain identical code, however the

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?

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745658865a4638712.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信