开发者

Can currying be used with lambda functions?

This piece o开发者_如何学Pythonf code fails to compile and I don't know if it is because it can not be done, lambdas do not inherit from binary_function, or it is just that I'm getting the syntax wrong

#include <functional>

int main(int argc, const char *argv[])
{
   auto lambda = [](int x, int y) -> int { return x + y; };
   auto sumFive = std::bind1st(lambda, 5); 

   return 0;
}


Use:

auto sumFive = std::bind(lambda, 5, std::placeholders::_1);

Please forget entirely about bind1st and binary_function, etc. Those were crutches in the old C++ because of the lack of lambdas and variadic templates. In C++11, use std::function and std::bind.


std::bind1st and std::bind are redundant in C++11. Just use another lambda:

auto lambda = [](int x, int y) { return x + y; };
auto sumFive = [&](int y) { return lambda(5, y); };

This is clearer and simpler (no need to know what std::bind does or what the std::placeholders are for), more flexible (it can support any expression, not just parameter binding), requires no support headers, and will probably compile a little faster too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜