Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 Lambda Passing with Capture [duplicate]

Tags:

c++

c++11

lambda

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
like image 759
Nyaarium Avatar asked Aug 28 '14 10:08

Nyaarium


People also ask

What is the correct syntax for lambda expression in C++11?

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; };

How do you capture a member variable in lambda?

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){ //.... }

How do you pass a lambda function in C++?

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.

Can a lambda capture itself?

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).


1 Answers

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();
}
like image 65
quantdev Avatar answered Oct 17 '22 09:10

quantdev