c++ - How std::bind can be used? -


one simple example explains how std::bind can used follows:

assume have function of 3 arguments: f3(x, y, z). want have function of 2 arguments defined as: f2(x,y) = f3(x,5,y). in c++ can std::bind:

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

this example clear me: std::bind takes function first argument , takes n other arguments, n number of arguments of function taken first argument std::bind.

however, found use of bind:

void foo( int &x ) {   ++x; }   int main() {   int = 0;    // binds copy of   std::bind( foo, ) (); // <------ line not understand.   std::cout << << std::endl;  } 

it clear foo has 1 argument , std::bind set i. but why use pair of brackets after (foo, i)? , why not use output of std::bind? mean, why don't have auto f = std::bind(foo, i)?

the line

std::bind( foo, ) (); 

is equivalent to:

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

it creates bound functor, calls (using second pair of parenthesis).

edit: in name of accuracy (and pointed out @roman, @daramarak) 2 not actually equivalent calling function directly: passed value std::bind. code equivalent calling foo directly i, be:

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

Comments