7

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
Nyaarium
  • 1,540
  • 5
  • 18
  • 34

1 Answers1

12

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();
}
quantdev
  • 23,517
  • 5
  • 55
  • 88