I have a base class where currently I have a method called get_value() which should return values converted appropriately to various primitive data types. Since, we cannot have virtual methods which differ by only return types, I had to do the following:
virtual void get_value(unsigned int index, unsigned char & r) const = 0;
virtual void get_value(unsigned int index, char & r) const = 0;
virtual void get_value(unsigned int index, unsigned short & r) const = 0;
virtual void get_value(unsigned int index, short & r) const = 0;
virtual void get_value(unsigned int index, unsigned int & r) const = 0;
virtual void get_value(unsigned int index, int & r) const = 0;
virtual void get_value(unsigned int index, float & r) const = 0;
virtual void get_value(unsigned int index, double & r) const = 0;
This is quite annoying from a maintenance point of view and also the usage is a bit awkward as the user has to do something like:
unsigned char v;
obj->get_value(100, v);
Anyways, the fact that all the child classes have to override for each of these types is annoying. I was wondering if anyone has any suggestions to avoid this or somehow be able to do this in a more compact way by having just one virtual function somehow.
A child class could be something like:
void get_value(unsigned int index, unsigned char & r) const {get<unsigned char>(index, r);}
void get_value(unsigned int index, char & r) const {get<char>(index, r);}
void get_value(unsigned int index, unsigned short & r) const {get<unsigned short>(index, r);}
void get_value(unsigned int index, short & r) const {get<short>(index, r);}
void get_value(unsigned int index, unsigned int & r) const {get<unsigned int>(index,r);}
void get_value(unsigned int index, int & r) const {get<int>(index,r);}
void get_value(unsigned int index, float & r) const {get<float>(index,r);}
void get_value(unsigned int index, double & r) const {get<double>(index,r);}
where this specialised templates get method does something specific for each child class.
You should consider just creating different functions.
int getInt();
double getDouble();
And so on.
It seems that your calling code has to know the difference in any case. Since there is no real abstraction on the operations you can perform (apparently, at least), you may as well make the difference clear. Templates and object-oriented classes may just add needless complexity.
Of course, in order to judge this, one would probably need more context. Just my 0.02 € :)
You might want to take a look at templates. They will allow you specify the type like so:
foo<float>(bar); // calls the float version
foo<int>(bar); // calls the int version
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With