Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to overload a function at runtime?

I'd like to streamline a code that has about a hundred of expressions like this:

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

Where AddData is overloaded as

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

I'd like to express the code above like this:

AddData( key, flag? some_number : error_description );

which, of course, won't compile because the value of the flag is determined at runtime and AddData signature needs to be determined at compile time.

Combining both functions into something like

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

and resolving which of the parameters to use and which one to ignore would work, but it just doesn't look pretty enough.

Thus the question: is it possible to resolve function overloading at runtime in a more reasonable manner?

like image 236
Michael Avatar asked Oct 20 '22 18:10

Michael


1 Answers

Just define a small helper in the function, and use that:

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, that's a simple change:

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

Depend on the compiler for optimization.

like image 122
Deduplicator Avatar answered Nov 02 '22 03:11

Deduplicator