Reputation: 237
How to use binder2nd, bind2nd, and bind1st? More specifically when to use them and are they necessary? Also, I'm looking for some examples.
Upvotes: 1
Views: 1543
Reputation: 24561
Binders are the C++ way of doing currying. BTW, check out Boost Bind library
Upvotes: 1
Reputation: 881605
They're never, strictly speaking, necessary, as you could always define your own custom functor object; but they're very convenient exactly in order to avoid having to define custom functors in simple cases. For example, say you want to count the items in a std::vector<int>
that are > 10
. You COULD of course code...:
std::count_if(v.begin(), v.end(), gt10())
after defining:
class gt10: std::unary_function<int, bool>
{
public:
result_type operator()(argument_type i)
{
return (result_type)(i > 10);
}
};
but consider how much more convenient it is to code, instead:
std::count_if(v.begin(), v.end(), std::bind1st(std::less<int>(), 10))
without any auxiliary functor class needing to be defined!-)
Upvotes: 5