How can currying be done in C++?

前端 未结 10 1392
余生分开走
余生分开走 2020-11-28 03:39

What is currying?

How can currying be done in C++?

Please Explain binders in STL container?

10条回答
  •  無奈伤痛
    2020-11-28 04:07

    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 
    #include 
    #include 
    
    using namespace std;
    
    // declare a binary function object
    class adder: public binary_function {
    public:
        int operator()(int x, int y) const
        {
            return x + y;
        }
    };
    
    int main()
    {
        // initialise some sample data
        vector 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::iterator i = b.begin(); i != b.end(); ++i) {
            cout << "  " << *i << endl;
        }
        cout << "]" << endl;
    
        return 0;
    }
    

提交回复
热议问题