fork download
  1. #include <iostream>
  2. #include <functional>
  3. using namespace std;
  4.  
  5. class Inner
  6. {
  7. int myx;
  8. public:
  9. Inner(int x); // this represents the capture of the lambda
  10. int operator()(int k); // this is the function of adding k to the catpture
  11. };
  12.  
  13. Inner::Inner(int x)
  14. {
  15. myx = x;
  16. }
  17. int Inner::operator()(int k)
  18. {
  19. cout << "Class Inner arg:" <<k<<" with a capture of "<<myx<<endl;
  20. return myx + k;
  21. }
  22.  
  23. class Suma
  24. {
  25. public:
  26. Inner operator()(int x);
  27. };
  28.  
  29. Inner Suma::operator()(int x)
  30. {
  31. cout<<"Class Suma is the function "<<x<<"+ something"<<endl;
  32. return Inner(x);
  33. };
  34.  
  35.  
  36. int main() {
  37.  
  38. auto lsuma = [](int x)->function<int(int)> // lsuma is a local lambda
  39. {
  40. cout<<"Suma lambda is the function "<<x<<"+ something"<<endl;
  41. return [x](int y)
  42. {
  43. cout << "inner lambda arg:" <<y<<" with a capture of "<<x<<endl;
  44. return x+y;
  45. };
  46. };
  47.  
  48.  
  49. Suma f; // f is also a local, but an object
  50. cout << lsuma(3)(2) <<endl;
  51. cout << f(3)(2)<<endl;
  52.  
  53. return 0;
  54. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
Suma lambda is the function 3+ something
inner lambda arg:2 with a capture of 3
5
Class Suma is the function 3+ something
Class Inner arg:2 with a capture of 3
5