Problem with virtual function design

I have a base class where I currently have a method called get_value () that should return values ​​that are converted accordingly to various primitive data types. Since we cannot have virtual methods that differ only in 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 in terms of maintenance, and the use is a bit inconvenient as the user should do something like:

unsigned char v;
obj->get_value(100, v);

In any case, the fact that all child classes must be redefined for each of these types is annoying. I was wondering if anyone has any suggestions to avoid this, or somehow make it more compact, with as many virtual functions as possible.

:

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);}

- .

+4
3

.

int getInt();
double getDouble();

.

, . , (-, ) , . - .

, , , , . 0,02 €:)

+5

templates. :

foo<float>(bar); // calls the float version
foo<int>(bar); // calls the int version
+4

You can have one call to a virtual function that returns boost::variantas follows:

using vartype = boost::variant<
    unsigned char,
    char,
    unsigned short,
    short,
    // ...
>;
virtual vartype get_value(unsigned int index) const = 0;
+1
source

Source: https://habr.com/ru/post/1530478/


All Articles