Is it possible to pass a lambda function as a function pointer? If so, I must be doing something incorrectly because I am getting a compile error.
Consider the following example
using DecisionFn = bool(*)();
class Decide
{
public:
Decide(DecisionFn dec) : _dec{dec} {}
private:
DecisionFn _dec;
};
int main()
{
int x = 5;
Decide greaterThanThree{ [x](){ return x > 3; } };
return 0;
}
When I try to compile this, I get the following compilation error:
In function 'int main()':
17:31: error: the value of 'x' is not usable in a constant expression
16:9: note: 'int x' is not const
17:53: error: no matching function for call to 'Decide::Decide(<brace-enclosed initializer list>)'
17:53: note: candidates are:
9:5: note: Decide::Decide(DecisionFn)
9:5: note: no known conversion for argument 1 from 'main()::<lambda()>' to 'DecisionFn {aka bool (*)()}'
6:7: note: constexpr Decide::Decide(const Decide&)
6:7: note: no known conversion for argument 1 from 'main()::<lambda()>' to 'const Decide&'
6:7: note: constexpr Decide::Decide(Decide&&)
6:7: note: no known conversion for argument 1 from 'main()::<lambda()>' to 'Decide&&'
That's one heck of an error message to digest, but I think what I'm getting out of it is that the lambda cannot be treated as a constexpr
so therefore I cannot pass it as a function pointer? I've tried making x
const as well, but that doesn't seem to help.
I know this a little bit old..
But i wanted to add:
Lambda expression (even captured ones) can be handled as a function pointer!
It is tricky because an Lambda expression is not a simple function. It is actually an object with an operator().
When you are creative, you can use this! Think of an "function" class in style of std::function. If you save the object!
You also can use the function pointer.
To use the function pointer, you can use the following:
To build a class that can start working like a "std::function" i will just do short example. First you need a class/struct than can store object and function pointer also you need an operator() to execute it:
With this you can now run captured, noncaptured lambdas, just like you are using the original:
This code works with VS2015 Hope it helps : )
Greets!
Edit: removed needles template FP, removed function pointer parameter, renamed to lambda_expression
Update 04.07.17:
Shafik Yaghmour's answer correctly explains why the lambda cannot be passed as a function pointer if it has a capture. I'd like to show two simple fixes for the problem.
Use
std::function
instead of raw function pointers.This is a very clean solution. Note however that it includes some additional overhead for the type erasure (probably a virtual function call).
Use a lambda expression that doesn't capture anything.
Since your predicate is really just a boolean constant, the following would quickly work around the current issue. See this answer for a good explanation why and how this is working.
Capturing lambdas cannot be converted to function pointers, as this answer pointed out.
However, it is often quite a pain to supply a function pointer to an API that only accepts one. The most often cited method to do so is to provide a function and call a static object with it.
This is tedious. We take this idea further and automate the process of creating
wrapper
and make life much easier.And use it as
Live
This is essentially declaring an anonymous function at each occurrence of
fnptr
.Note that invocations of
fnptr
overwrite the previously writtencallable
given callables of the same type. We remedy this, to a certain degree, with theint
parameterN
.As it was mentioned by the others you can substitute Lambda function instead of function pointer. I am using this method in my C++ interface to F77 ODE solver RKSUITE.
While the template approach is clever for various reasons, it is important to remember the lifecycle of the lambda and the captured variables. If any form of a lambda pointer is is going to be used and the lambda is not a downward continuation, then only a copying [=] lambda should used. I.e., even then, capturing a pointer to a variable on the stack is UNSAFE if the lifetime of those captured pointers (stack unwind) is shorter than the lifetime of the lambda.
A simpler solution for capturing a lambda as a pointer is:
auto pLamdba = new std::function<...fn-sig...>([=](...fn-sig...){...});
e.g.,
new std::function<void()>([=]() -> void {...}
Just remember to later
delete pLamdba
so ensure that you don't leak the lambda memory. Secret to realize here is that lambdas can capture lambdas (ask yourself how that works) and also that in order forstd::function
to work generically the lambda implementation needs to contain sufficient internal information to provide access to the size of the lambda (and captured) data (which is why thedelete
should work [running destructors of captured types]).A lambda can only be converted to a function pointer if it does not capture, from the draft C++11 standard section
5.1.2
[expr.prim.lambda] says (emphasis mine):Note, cppreference also covers this in their section on Lambda functions.
So the following alternatives would work:
and so would this:
and as 5gon12eder points out, you can also use
std::function
, but note thatstd::function
is heavy weight, so it is not a cost-less trade-off.