1

Referencing What is a lambda (function)?

I noticed there was not a C++ solution among the interesting answers.

So I played a little with a C++ solution.

I wonder if this code is a valid C++ version of the adder() function ?

//to accept the 19 i need a rvalue ref.
auto adder = [](int&& x) {  auto rv = [&x](int y) {return  x + y;  };return rv;};
//the similar line to most examples:
auto add5 = adder(19);
std::cout<<"val : "<<add5(4);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 2
    "[T]o accept the 19 i need a rvalue ref" is incorrect. You could use a *value* argument (i,e, plain `int`) as well (similar to what you do with the `y` argument in the nested lambda). Also note that you need to capture `x` by value to bypass possible lifetime issues. – Some programmer dude Mar 13 '21 at 21:15

1 Answers1

0

Yes thats a completely valid lambda expression.

It's not apparent what is the advantage of nesting is in your example. Though consider a function:

int add(int a, int b) { return a + b; }

When you want to bind a particular value to one of the parameters to get a function you can call with one parameter you can use a lambda expression. And if you want to bind different values you can use a nested lambda expression:

auto add_x = [](int x){ return [x](int y){ return add(x,y); };};
auto add_3 = add_x(3);
auto add_7 = add_x(7);
std::cout << add_3(5);   // prints 8
std::cout << add_7(5);   // prints 12
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185