For this simplified piece of code I'm getting following error:
error: too few arguments to function std::cout << f();
int g(int a = 2, int b = 1)
{
return a + b;
}
template<class Func>
void generic(Func f)
{
std::cout << f();
}
int main()
{
generic(g);
}
I cannot clue the reason for why the default parameters of function f
are not passing into a function generic
. It behaves like f
doesn't have any default parameters ...
What's wrong there?
How do I forward default parameters correctly?
Constructors cannot have 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.
All the parameters of a function can be default parameters.
A parameter with a default value, is often known as an "optional parameter". From the example above, country is an optional parameter and "Norway" is the default value.
g
may have default arguments, but the type of &g
is still int(*)(int, int)
, which is not a type that can be called with no arguments. Within generic
, we can't differentiate that - we've already lost the context about default arguments.
You can just wrap g
in a lambda to preserve the context:
generic([]{ return g(); });
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