How can currying be done in C++?

前端 未结 10 1399
余生分开走
余生分开走 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:00

    Other answers nicely explain binders, so I won't repeat that part here. I will only demonstrate how currying and partial application can be done with lambdas in C++0x.

    Code example: (Explanation in comments)

    #include 
    #include 
    
    using namespace std;
    
    const function & simple_add = 
      [](int a, int b) -> int {
        return a + b;
      };
    
    const function(int)> & curried_add = 
      [](int a) -> function {
        return [a](int b) -> int {
          return a + b;
        };
      };
    
    int main() {
      // Demonstrating simple_add
      cout << simple_add(4, 5) << endl; // prints 9
    
      // Demonstrating curried_add
      cout << curried_add(4)(5) << endl; // prints 9
    
      // Create a partially applied function from curried_add
      const auto & add_4 = curried_add(4);
      cout << add_4(5) << endl; // prints 9
    }
    

提交回复
热议问题