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?
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.
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