Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't pass lambda with reference capture

Following code fails with this error

E0413 no suitable conversion function from "lambda []float (int i)->float" to "float (*)(int i)" exists

int test;   
float (*f)(int i) = [&](int i) -> float {return test; };

How do I fix this? I need the Capture clause.

like image 500
M.kazem Akhgary Avatar asked Sep 23 '19 04:09

M.kazem Akhgary


People also ask

Does lambda capture reference by value?

The mutable keyword is used so that the body of the lambda expression can modify its copies of the external variables x and y , which the lambda expression captures by value. Because the lambda expression captures the original variables x and y by value, their values remain 1 after the lambda executes.

Is a C++ lambda a function pointer?

C++ Lambdas Conversion to function pointer This feature is mainly useful for using lambdas with APIs that deal in function pointers, rather than C++ function objects. Conversion to a function pointer is also possible for generic lambdas with an empty capture list.

What does it mean to lambda capture this?

The lambda is capturing an outside variable. A lambda is a syntax for creating a class. Capturing a variable means that variable is passed to the constructor for that class. A lambda can specify whether it's passed by reference or by value.


1 Answers

You can only do the above with capture-less lambdas.

See [expr.prim.lambda.closure] (sec 7)

The closure type for a non-generic lambda-expression with no lambda-capture whose constraints (if any) are satisfied has a conversion function to pointer to function with C++ language linkage having the same parameter and return types as the closure type's function call operator.

Since lambdas are not just ordinary functions and capturing it need to preserve a state, you can not find any simple or conventional solution to make them assign to function pointers.


To fix, you can use std::function which will do it by type erasure:

#include <functional> // std::function

int test;
std::function<float(int)> f = [&](int i) -> float {return static_cast<float>(test); };
like image 71
JeJo Avatar answered Sep 25 '22 23:09

JeJo