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条)