Is there a good method for writing C / C++ function headers with default parameters that are function calls?
I have some header with the function:
int foo(int x, int y = 0);
I am working in a large code base where many functions call this function and depend on this default value. This default value now needs to change to something dynamic and I am looking for a way to do:
int foo(int x, int y = bar());
Where bar() is some function that generates the default value based on some system parameters. Alternatively this function prototype would look like:
int foo(int x, int y = baz.bar());
Where baz is a function belonging to an object that has not been instantiated within the header file.
Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.
All the parameters of a function can be default parameters.
The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.
An IN OUT parameter cannot have a default value. An IN OUT actual parameter or argument must be a variable.
Go figure! It does work. Default arguments in C++ functions
I would use two overloaded functions:
int foo(int x, int y);
int foo(int x){return foo(x,bar);}
If you allow the forwarding function to be inlined, then the performance penalty is likely to small to zero. If you keep the body of it out of line in a non-header file there may be a performance cost (likely to be small), but much more flexibility in implementation and reduced coupling.
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