views:

268

answers:

2

How to use binder2nd, bind2nd, and bind1st? More specifically when to use them and are they necessary? Also, I'm looking for some examples.

+5  A: 

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!-)

Alex Martelli
Right, I understand that, however what about this?bool IsOdd (int i) { return ((i%2)==1); }int main () { int mycount; vector<int> myvector; for (int i=1; i<10; i++) myvector.push_back(i); // myvector: 1 2 3 4 5 6 7 8 9 mycount = (int) count_if (myvector.begin(), myvector.end(), IsOdd); cout << "myvector contains " << mycount << " odd values.\n"; return 0;}It's from: http://www.cplusplus.com/reference/algorithm/count_if/They are not defining any functor objects, just a simple function
Tom
Sorry I didn't format the code, but the code is here:http://www.cplusplus.com/reference/algorithm/count_if/
Tom
@Tom, yes, in trivially simple cases the functor can be a function, but, again, you've got to define it previously (often far from the point of use) -- the binders are _convenient_ because they let you avoid that (never _necessary_, as I already said: just _convenient_!-).
Alex Martelli
+1  A: 

Binders are the C++ way of doing currying. BTW, check out Boost Bind library

Nemanja Trifunovic