Bind
Header: "boost/bind.hpp"
The Bind library creates function objects that bind to a function (free function or member function). Rather than supplying all of the arguments to the function directly, arguments can be delayed, meaning that a binder can be used to create a function object with changed arity (number of arguments) for the function it binds to, or to reorder the arguments any way you like.
The return types of the overloaded versions of the function bind are unspecified—that is, there is no guarantee for what the signature of a returned function object is. Sometimes, you need to store that object somewhere, rather than just passing it directly to another function—when this need arises, you want to use Boost.Function, which is covered in "Library 11: Function 11." The key to understanding what the bind-functions return is to grok the transformation that is taking place. Using one of the overloaded bind functions—template<class R, class F> unspecified-1 bind(F f)—as an example, this would be (quoting from the online documentation), "A function object l such that the expression l(v1, v2, ..., vm) is equivalent to f(), implicitly converted to R." Thus, the function that is bound is stored inside the binder, and the result of subsequent invocations on that function object yields the return value from the function (if any)—that is, the template parameter R. The implementation that we're covering here supports up to nine function arguments.
The implementation of Bind involves a number of functions and classes, but as users, we do not directly use anything other than the overloaded function bind. All binding takes place through the bind function, and we can never depend on the type of the return value. When using bind, the placeholders for arguments (called _1, _2, and so on) do not need to be introduced with a using declaration or directive, because they reside in an unnamed namespace. Thus, there is rarely a reason for writing one of the following lines when using Boost.Bind.
using boost::bind; using namespace boost;
As was mentioned before, the current implementation of Boost.Bind supports nine placeholders (_1, _2, _3, and so forth), and therefore also up to nine arguments. It's instructive to at least browse through the synopsis for a high-level understanding of how the type deduction is performed, and when/why this does not always work. Parsing the signatures for member function pointers and free functions takes a while for the eye to get used to, but it's useful. You'll see that there are overloads for both free functions and class member functions. Also, there are overloads for each distinct number of arguments. Rather than listing the synopsis here, I encourage you to visit Boost.Bind's documentation at www.boost.org.