Scott Zhou
Scott Zhou

Reputation: 83

How to do function currying before c++11

I have a function which have two arguments, and I want bind the 2nd argument to a value and get a new function object.

What I want is perfectly supported by std::bind in c++ 11, for example:

int my_func(int a, int b) {...}
auto bind_func = std::bind (my_func,_1, 555);

Or in python:

bind_func = functools.partial(my_func, b=555)

But I want to do it in C++03, I know boost can do it but I don't want invoke boost for this simple requirement.

Now I wrote my own template to do it, but it will be perfect if I can use standard library.

Does anyone know how can I do it?

Thanks!

Upvotes: 2

Views: 241

Answers (1)

Michaël Roy
Michaël Roy

Reputation: 6471

A functor is very easy to make. And that's the only way of currying functions in pre 2011 c++.

Example:

struct my_func_functor  // choose a name
{
    int curry_;
    my_func_functor(int curry) : curry_(curry) {}
    int operator()(int a) { return my_func(a, curry_); }
};


// to use...
vector<int> v;

//...

// build the functor with the curry and let transform do the cooking...
std::transform(v.begin(), v.end(), v.begin(), my_func_functor(555));

You can of course store anything you want in the functor. including references. This is the same model used behind the scene by C++11's lambdas. Instead of a capture clause, you have a constructor, and a structure to hold the data to pass along when the actual call is made through the operator().

Upvotes: 1

Related Questions