How can I bind to a function that takes default arguments, without specifying the default arguments and then call it without any arguments?
void foo(int a, int b = 23) { std::cout << a << " " << b << std::endl; } int main() { auto f = std::bind(foo, 23, 34); // works f(); auto g = std::bind(foo, 23); // doesn't work g(); using std::placeholders::_1; auto h = std::bind(foo, 23, _1); // doesn't work either h(); }
In C++ programming, we can provide default values for function parameters. If a function with default arguments is called without passing arguments, then the default parameters are used. However, if arguments are passed while calling the function, the default arguments are ignored.
No you cannot overload functions on basis of value of the argument being passed, So overloading on the basis of value of default argument is not allowed either. You can only overload functions only on the basis of: Type of arguments. Number of arguments.
Default arguments are only allowed in the parameter lists of function declarations and lambda-expressions, (since C++11) and are not allowed in the declarations of pointers to functions, references to functions, or in typedef declarations.
Basically, any time you write foo(x)
the compiler translates it to foo(x, 23);
. It only works if you actually have a directly call with the function name. You can' t, for example, assign &foo
to a void(*)(int)
, because the function's signature is void(int, int)
. Default parameters play no part in the signature. And if you assign it to a void(*)(int, int)
variable, the information about the default parameter is lost: you can't take advantage of the default parameter through that variable. std::bind
stores a void(*)(int, int)
somewhere in its bowels, and thus loses the default parameter information.
There is no way in C++ to get the default value of a parameter from outside the function, so you're stuck with manually providing the default value when you bind.
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