std::function and std::bind
The bind and function standard function objects are defined in <functional> (together with a lot of other function objects); they are used to handle functions and function arguments. bind is used to take a function (or a function object or anything you can invoke using the (...) syntax) and produce a function object with one or more of the arguments of the argument function ``bound'' or rearranged. For example:int f(int,char,double); auto ff = bind(f,_1,'c',1.2); // deduce return type int x = ff(7); // f(7,'c',1.2);This binding of arguments is usually called ``Currying.'' The _1 is a place-holder object indicating where the first argument of ff is to go when f is called through ff . The first argument is called _1 , the second _2 , and so on. For example:
int f(int,char,double); auto frev = bind(f,_3,_2,_1); // reverse argument order int x = frev(1.2,'c',7); // f(7,'c',1.2);Note how auto saves us from having to specify the type of the result of bind .
It is not possible to just bind arguments for an overloaded function, we have to explicitly state which version of an overloaded function we want to bind:
int g(int); double g(double); // g() is overloaded auto g1 = bind(g,_1); // error: which g()? auto g2 = bind((double(*)(double))g,_1); // ok (but ugly)bind() comes in two variants: the one shown above and a "legacy" version where you explicitly specify the return type:
auto f2 = bind<int>(f,7,'c',_1); // explicit return type int x = f2(1.2); // f(7,'c',1.2);This second version was necessary and is widely used because the first (and for a user simplest) version cannot be implemented in C++98.
function is a type that can hold a value of just about anything you can invoke using the (...) syntax. In particular, the result of bind can be assigned to afunction. function is very simple to use. For example:
function<float (int x, int y)> f; // make a function object struct int_div { // take something you can call using () float operator()(int x, int y) const { return ((float)x)/y; }; }; f = int_div(); // assign cout << f(5, 3) << endl; // call through the function object std::accumulate(b,e,1,f); // passes beautifullyMember functions can be treated as free functions with an extra argument
struct X { int foo(int); }; function<int (X*, int)> f; f = &X::foo; // pointer to member X x; int v = f(&x, 5); // call X::foo() for x with 5 function<int (int)> ff = std::bind(f,&x,_1); // first argument for f is &x v=ff(5); // call x.foo(5)function s are useful for callbacks, for passing operations as argument, etc. It can be seen as a replacement for the C++98 standard library function objects mem_fun_t , pointer_to_unary_function , etc. Similarly, bind() can be seen as a replacement for bind1() and bind2() .
See also:
- Standard: 20.7.12 Function template bind, 20.7.16.2 Class template function
- Herb Sutter: Generalized Function Pointers. August 2003.
- Douglas Gregor: Boost.Function.
- Boost::bind