Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a lambda expression with variable capture to a function pointer [duplicate]

Tags:

c++

lambda

I'm trying to use lambda functions to quickly test things out, and I'm running up against a wall with it. I have no idea why things aren't working as (I feel) they should be.

This works as I would expect:

double(*example)(double) = [](double S)->double {return std::max(1-100/S, 0.0) * LogNormal(S, 100, 0.25); };
NewtonCotes(lowerBound, upperBound, example, intervals, order)

However this does not:

double(*example)(double) = [K](double S)->double {return std::max(1 - K / S, 0.0) * LogNormal(S, 100, 0.25); };

Giving the error:

Error: no suitable conversion function from "lambda []double(double S)->double" to "double(*)(double)" exists.

I do not understand why adding something to the capture list should change what's going on here. I'm fairly new to lambdas in C++ though, so could be making a silly mistake somewhere...

What do I need to do to get this to work? I've seen a few people noting that there was a bug in intellisense, and that something like this should work, though it was a slightly different issue (at least i didn't think they matched exactly). I'm also using VS2013, rather than 2011 where that bug was mentioned.

like image 974
will Avatar asked Jul 24 '15 13:07

will


1 Answers

The reason for that is the capture - if a lambda captures anything if cannot be represented as a function pointer.

That makes sense if you think that to capture any variables the compiler has to create a new type that will store the captured variables and provide non-static operator() - so the object returned by lambda expression has state and cannot be converted to a plain function pointer.

like image 128
Alexander Balabin Avatar answered Sep 19 '22 18:09

Alexander Balabin