Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I bind to a function that takes default arguments and then call it?

Tags:

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();  } 
like image 959
Stephan Dollberg Avatar asked May 23 '12 11:05

Stephan Dollberg


People also ask

How can we pass default arguments to a function?

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.

Can we pass default arguments to overloaded functions?

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.

Which case default argument passing in function is not allowed?

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.


1 Answers

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.

like image 133
R. Martinho Fernandes Avatar answered Nov 11 '22 02:11

R. Martinho Fernandes