Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

virtual function design issue

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.

like image 300
Luca Avatar asked Dec 25 '22 12:12

Luca


2 Answers

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 € :)

like image 177
Christian Hackl Avatar answered Dec 28 '22 07:12

Christian Hackl


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
like image 39
OMGtechy Avatar answered Dec 28 '22 05:12

OMGtechy