Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How std::bind can be used?

Tags:

c++

std

bind

One simple example that explains how std::bind can be used is as follows:

Assume that we have a function of 3 arguments: f3(x, y, z). We want to have a function of 2 arguments that is defined as: f2(x,y) = f3(x,5,y). In C++ we can easily do it with std::bind:

auto f2 = std::bind(f3, _1, 5, _2);

This example is clear to me: std::bind takes a function as its first argument and then it takes n other arguments, where n is the number of arguments of the function that is taken as the first argument for std::bind.

However, I found another use of bind:

void foo( int &x )
{
  ++x;
}


int main()
{
  int i = 0;

  // Binds a copy of i
  std::bind( foo, i ) (); // <------ This is the line that I do not understand.
  std::cout << i << std::endl;

}

It is clear that foo has one argument and with std::bind it was set to i. But but why do we use another pair of brackets after (foo, i)? And why we do not use output of the std::bind? I mean, why don't we have auto f = std::bind(foo, i)?

like image 861
Roman Avatar asked Mar 21 '13 08:03

Roman


Video Answer


3 Answers

The line

std::bind( foo, i ) ();

is equivalent to:

auto bar = std::bind( foo, i );
bar();

It creates a bound functor, then immediately calls it (using the second pair of parenthesis).

Edit: In the name of accuracy (and pointed out by @Roman, @daramarak) the two are not actually equivalent to calling the function directly: the i is passed by value to std::bind. The code equivalent to calling foo directly with i, would be:

auto bar = std::bind( foo, std::ref(i) );
bar();
like image 164
utnapistim Avatar answered Oct 23 '22 07:10

utnapistim


It binds foo to a temporary object and then call it immediately:

  auto f = std::bind(foo, i);
  f();

Single line version:

std::bind(foo, i)();
like image 37
masoud Avatar answered Oct 23 '22 09:10

masoud


Your two questions pretty much answer each other. The trailing () is just a normal function call. Therefore, the expression means: "Bind i to foo; this will yield a function taking no parameters; then call the resulting function." Since the code's author decided the function is no longer needed after being called, it's not stored anywhere.

like image 2
Angew is no longer proud of SO Avatar answered Oct 23 '22 09:10

Angew is no longer proud of SO