How can I use std :: bind?

One simple example explaining how to use std::bindit is as follows:

Suppose we have a function of 3 arguments: f3 (x, y, z). We want to be a function of two arguments, which is defined as: f2(x,y) = f3(x,5,y). In C ++, we can easily do this with std::bind:

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

This example is clear to me: it std::bindtakes a function as its first argument, and then takes another n arguments, where n is the number of arguments to the function, which is taken as the first argument to 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;

}

, foo , std::bind i. (foo, i)? std::bind? , auto f = std::bind(foo, i)?

+5
4

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

:

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

, ( ).

: ( @Roman, @daramarak) : std:: bind. , foo i, :

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

foo , :

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

:

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

. () - . , : " i foo, , , ". , , .

+2

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

... , ...

foo(i);

... "" std:: bind, , , std:: bind, .

, - , std:: bind.

0
source

All Articles