Will the parameters on the function pointer with default parameters be discarded?

I am trying to call an overloaded function that works with function pointers that have parameters with default values.

void originalFunction1 (int a = 0) {printf("I'm #1 and a is %d",a);} void originalFunction2 () {printf("I'm #2");} void overloadedFunction (void (*fptr)(void)) { fptr(); } void overloadedFunction (void (*fptr)(int)) { overloadedFunction( (void(*)(void)) fptr); } int main() { overloadedFunction(originalFunction1); overloadedFunction(originalFunction2); // output is: // I'm #1 an a is -1073743272 // I'm #2 } 

As the answers to this question indicate, the default values ​​are not part of the function signature, nor can they be repeated during the (function pointer -) parameter definition. As my example shows, they can be discarded for a call, but they will not be initialized by default.

Is there any way around this?

I cannot change the original function, but I know the default value. I can change both the main overloaded function and the redirects. Fptr will always be called without parameters. Actually, there are more overloaded functions, as the return type is different, but I can easily drop it.

+6
source share
1 answer

The short answer is no. Casting is legal, but the only thing you can do with the results is to return them to the original type. The arguments by default do not change the signature function. They are only counted on the call site, where they are transferred if the client does not provide an argument. the function itself is always called with a full set of arguments, which obviously will not happen if you call it based on the results of the actors.

The usual answer here, if you have control over the sources, is to use overloading instead of the default arguments. (I heard the arguments that you should always use overloading instead of the default arguments.) So

 void originalFunction1( int a ) { ... } void originalFunction1() { originalFunction1( 0 ); } 

instead of what you have.

In addition, you can play games with templates:

 template <typename FunctionPtr> void overloadedFunction( FunctionPtr fptr ) { fptr(); } 

I would prefer the first solution if you can use it.

+2
source

All Articles