c++ variable Binding a const function reference to a lambda

std::function member function (2)

This code

int(&foo)(int, int) = [](int a, int b) { return a + b; };

doesn't compile since apparently a non-const reference can't be initialized with a temporary. Where do I put the const ?

As mentioned already, a capture-less lambda is convertible to a function pointer. So if you want to bind that static function to a reference, you need to dereference the pointer.

int(&foo)(int, int) = *[](int a, int b) { return a + b; };

Applying * to the lambda causes a bunch of machinery to kick in. Since the lambda doesn't overload operator* , but does implement a conversion to a pointer type, that conversion happens. Afterwards * is applied to the returned pointer and that yields a function lvalue. That lvalue can then bind to the reference.

Here it is live .

A lambda can only be converted to a function pointer if it does not capture.


[Lambda Functions][1]

I changed your code as below and it worked.

int main()
   cout << "Res:: " << foo(10,20);
   return 0;

I just make it function pointer.


auto foo = [](int a, int b) { return a + b; }; 

is also a good choice.

I hope it helps!