I'm trying to pass a lambda function with capture [&]. What is the correct declaration for a variable storing a capturing lambda? [f2 below]
// Non-capturing
void (*f1)() = [](){ }; // Works
// All by reference
void (*f2)() = [&](){ }; // Syntax Error
Lambdas can both capture variables and accept input parameters. A parameter list (lambda declarator in the Standard syntax) is optional and in most aspects resembles the parameter list for a function. auto y = [] (int first, int second) { return first + second; };
To capture the member variables inside lambda function, capture the “this” pointer by value i.e. std::for_each(vec. begin(), vec. end(), [this](int element){ //.... }
Permalink. All the alternatives to passing a lambda by value actually capture a lambda's address, be it by const l-value reference, by non-const l-value reference, by universal reference, or by pointer.
Example# But a lambda cannot be recursive, it has no way to invoke itself. A lambda has no name and using this within the body of a lambda refers to a captured this (assuming the lambda is created in the body of a member function, otherwise it is an error).
The C++ Standard, section § 5.1.2 / 6 : [expr.prim.lambda]
The closure type for a non-generic lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function with C ++ language linkage (7.5) having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator
Since your lambda has a capture (a default one : [&]
), there is no conversion operator to a pointer to function.
Alternatively, you can use std::function<>
to wrap your lambda :
#include <functional>
#include <iostream>
int main()
{
int i = 42;
std::function<void(void)> f = [&](){ std::cout << i; };
f();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With