最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin4PV0评论

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?

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far