1

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

Tom
  • 217
  • 1
  • 5
  • 10

2 Answers2

5

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
  • 854,459
  • 170
  • 1,222
  • 1,395
  • Right, I understand that, however what about this? bool IsOdd (int i) { return ((i%2)==1); } int main () { int mycount; vector 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 Sep 21 '09 at 16:49
  • Sorry I didn't format the code, but the code is here: http://www.cplusplus.com/reference/algorithm/count_if/ – Tom Sep 21 '09 at 16:50
  • @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 Sep 21 '09 at 17:04
1

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

Nemanja Trifunovic
  • 24,346
  • 3
  • 50
  • 88