Is it possible to overload a function at runtime?

I would like to sort the code containing about a hundred expressions:

if( flag ) AddData( key, some_number ); else AddData( key, error_description ); 

Where adddata is overloaded like

 bool AddData( int key, double value ); bool AddData( int key, const char * error ); 

I would like to express the code above:

 AddData( key, flag? some_number : error_description ); 

which, of course, will not compile, because the flag value is determined at run time, and the AddData signature must be determined at compile time.

Combining both functions into something like

 bool AddData( int key, bool flag, double value, const char * error ); 

and decide which parameter to use and which to ignore will work, but it just doesn’t look enough.

So the question is: is it possible to more efficiently allow function overloading at runtime?

+5
source share
3 answers

Just define a little helper in the function and use this:

 auto AddHelper = [](bool flag, int key, double value, const char* error) { return flag ? AddData(key, value) : AddData(key, error); } 

If the flag is actually always the same, what a simple change:

 auto AddHelper = [flag](int key, double value, const char* error) { return flag ? AddData(key, value) : AddData(key, error); } 

Depends on the compiler for optimization.

+2
source

You might be better off using polymorphism instead of hundreds of ifs.

Instead of a flag, there is a polymorphic base class that performs data addition, and instead of changing the flag, you have chosen the correct derived class.

Then the calling code will be simple:

 data_adder->add(key, value, error_description); 

An example of a base class and derived classes:

 struct DataAdder { virtual void add(int key, double value, const char *error) = 0; protected: ~DataAdder(){}; }; struct ValueDataAdder : DataAdder { void add(int key, double value, const char*) override { AddData(key, value); } }; struct ErrorDataAdder : DataAdder { void add(int key, double, const char* error) override { AddData(key, error); } }; 

Live demo

+1
source

Given the assumption that none of the characters in the expression in question can be considered, the best you get is

 AddData(key, flag, some_number, error_description) 

If you can specify it so that perhaps flag is applied to multiple calls, then you can start to do better with a structure like

 Adder<flag>{} .AddData(key1, val1, error1) .AddData(key2, val2, error2) .AddData(...) . . 

those. "free" interface that remembers which side of if taken every time.

0
source

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


All Articles