Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost Lambda/Phoenix - how to do lambda which returns another lambda?

Does Boost Lambda/Phoenix supports out of box something like lambda which returns another lambda?

For instance, that can be used to do some kind of currying:

std::cout << [](int x){return [=](int y){return x+y;};}(1)(2);

How to achieve similar purpose with Boost Lambda/Phoenix (+ as a bonus - we would get polymorphic behaviour)?

like image 460
qble Avatar asked Feb 25 '13 21:02

qble


1 Answers

Boost Phoenix Scope: let/lambda

Live demo:

#include <boost/phoenix.hpp>
#include <iostream>
#include <ostream>

using namespace std;
using namespace boost;
using namespace phoenix;
using namespace arg_names;
using namespace local_names;

int main()
{
   // capture by reference:
   cout <<
      (lambda(_a=_1)[_1 + _a ])(1)(2)
   << endl;
   cout <<
      (lambda(_b=_1)[lambda(_a=_1)[_1 + _a + _b ]])(1)(2)(3)
   << endl;
   // capture by value:
   cout <<
      (lambda(_a=val(_1))[_1 + _a ])(1)(2)
   << endl;
   cout <<
      (lambda(_b=val(_1))[lambda(_a=val(_1))[_1 + _a + _b ]])(1)(2)(3)
   << endl;
}

Output is:

3
6
3
6
like image 117
Evgeny Panasyuk Avatar answered Oct 16 '22 14:10

Evgeny Panasyuk