C ++ 11 Lambda capture

I am trying to pass a lambda function with capture [&]. What is the correct declaration for a variable holding a lambda capture? [f2 below]

// Non-capturing void (*f1)() = [](){ }; // Works // All by reference void (*f2)() = [&](){ }; // Syntax Error 
+5
source share
1 answer

C ++ Standard, Section ยง 5.1.2 / 6: [expr.prim.lambda]

The closure type for a non-generic lambda expression without lambda capture has a public non-virtual implicit function of converting const to a function pointer with a C ++ language binding (7.5) with the same parameters and return types as the closure call statement. The value returned by this conversion function must be the address of a function that, when called, has the same effect as a call of the closure type. Function call statement

Since your lambda has a capture (default: [&] ), the conversion operator does not work with a function pointer.


Alternatively, you can use std::function<> to wrap the lambda:

 #include <functional> #include <iostream> int main() { int i = 42; std::function<void(void)> f = [&](){ std::cout << i; }; f(); } 
+10
source

Source: https://habr.com/ru/post/1201322/


All Articles