I know what functors are and when to use them with std algorithms, but I haven’t understood what Stroustrup says about them in the C++11 FAQ.
Can anyone explain what std::bind and std::function are, when they should be used, and give some examples for newbies?
std::bindis for partial function application.That is, suppose you have a function object
fwhich takes 3 arguments:You want a new function object which only takes two arguments, defined as:
gis a “partial application” of the functionf: the middle argument has already been specified, and there are two left to go.You can use
std::bindto getg:This is more concise than actually writing a functor class to do it.
There are further examples in the article you link to. You generally use it when you need to pass a functor to some algorithm. You have a function or functor that almost does the job you want, but is more configurable (i.e. has more parameters) than the algorithm uses. So you bind arguments to some of the parameters, and leave the rest for the algorithm to fill in:
Here,
powtakes two parameters and can raise to any power, but all we care about is raising to the power of 7.As an occasional use that isn’t partial function application,
bindcan also re-order the arguments to a function:I don’t recommend using it just because you don’t like the API, but it has potential practical uses for example because:
is a less-than-or-equal function (assuming a total order, blah blah). This example normally isn’t necessary since there already is a
std::less_equal(it uses the<=operator rather than<, so if they aren’t consistent then you might need this, and you might also need to visit the author of the class with a cluestick). It’s the sort of transformation that comes up if you’re using a functional style of programming, though.