c++stlfunctional-programmingcurryingbinders

How can currying be done in C++?


What is currying?

How can currying be done in C++?

Please Explain binders in STL container?


Solution

  • In short, currying takes a function f(x, y) and given a fixed Y, gives a new function g(x) where

    g(x) == f(x, Y)
    

    This new function may be called in situations where only one argument is supplied, and passes the call on to the original f function with the fixed Y argument.

    The binders in the STL allow you to do this for C++ functions. For example:

    #include <functional>
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    // declare a binary function object
    class adder: public binary_function<int, int, int> {
    public:
        int operator()(int x, int y) const
        {
            return x + y;
        }
    };
    
    int main()
    {
        // initialise some sample data
        vector<int> a, b;
        a.push_back(1);
        a.push_back(2);
        a.push_back(3);
    
        // here we declare a function object f and try it out
        adder f;
        cout << "f(2, 3) = " << f(2, 3) << endl;
    
        // transform() expects a function with one argument, so we use
        // bind2nd to make a new function based on f, that takes one
        // argument and adds 5 to it
        transform(a.begin(), a.end(), back_inserter(b), bind2nd(f, 5));
    
        // output b to see what we got
        cout << "b = [" << endl;
        for (vector<int>::iterator i = b.begin(); i != b.end(); ++i) {
            cout << "  " << *i << endl;
        }
        cout << "]" << endl;
    
        return 0;
    }