Currying & C++

C++ is cool, I didn’t know you could do this until yesterday. Unfortunately it’s a bit painful to bind anything other than the 1st or 2nd arguments (by painful I mean not-built-in).


#include <iostream>
#include <functional>
#include <vector>
using namespace std;
int main() {
vector<int> v;
vector<int>::iterator it;
v.push_back(3);
v.push_back(4);
for (it = v.begin(); it != v.end(); ++it) {
cout << *it << endl;
}
transform(v.begin(), v.end(), v.begin(), bind1st(plus<int>(), 3));
for (it = v.begin(); it != v.end(); ++it) {
cout << *it << endl;
}
return 0;
}

Also WordPress doesn’t like newlines or tabs in <code> </code> blocks? Lame!


  1. It doesn’t strike me as to how one would actually go about binding an arbitrary positional argument, which I suppose is why there isn’t an arbitrary ‘bindnth’ function that can be used to do exactly that.

    That said, I think it’s cool, too! (Just wish I knew about it before I gave my talk yesterday… grumble)

  2. You would need an nth_argument_type field in an nary_traits superclass… which unfortunately I don’t believe C++ can generate on the fly… but perhaps one could write a python script to produce the required templates on demand!

  3. Jayen

    just look at /usr/include/c++/4.3/backward/binders.h and write your own!

  4. In C++0x, with variadic templates, that won’t be necessary :-)




Leave a Comment