I have a piece of code, copied below, with really similar structs in which just one member changes type. I am looking to simplify it. I was considering using a template, but I am not too sure how would it be the syntax between a struct and a template. Any pointer would be greatly appreciated.
typedef struct pos_parameter{
float magnitud;
bool new_value;
} pos_parameter;
typedef struct feed_parameter{
double magnitud;
bool new_value;
} feed_parameter;
typedef struct speed_parameter{
long magnitud;
bool new_value;
} speed_parameter;
typedef struct g_code_parameter{
int magnitud;
bool new_value;
} g_code_parameter;
typedef struct position{
pos_parameter X;
pos_parameter Y;
pos_parameter Z;
pos_parameter A;
} position;
typedef struct move{
position pos;
feed_parameter feedrate;
speed_parameter speed;
g_code_parameter g_code;
} move;
One quick observation before we get in to genericizing the
magnitudmember variable. Your use of thetypedef struct {/*...*/} name;syntax is not needed, and very non-idiomatic in C++. In C this may be needed, but C++ is not C. In C++, you can simply:Now, in order to genericize the type of the
magnitudmember variable, you can create a class template like this:You would declare an instance of such a thing like this:
You can also use a
typedefto create a kind of “alias” for certian specializations ofbasic_parameter, like this:You can use this technique to create
typedefs for all the different kinds of parameters you were using in thepositionandmovestructures, and make it so that you don’t have to change the code for those types.Here is a complete solution: