9

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.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
will
  • 10,260
  • 6
  • 46
  • 69
  • 6
    See [Passing lambda as function pointer](http://stackoverflow.com/q/28746744/1708801) ... tl;dr lambda can only be converted to a function pointer if it does not capture. – Shafik Yaghmour Jul 24 '15 at 13:11
  • @ShafikYaghmour Yeah you weren't kidding about marking duplicates when you have an answer... – Barry Jul 24 '15 at 13:23
  • I did search for duplicates, but i've only jsut started looking at this today, and so when i say it's new to me, i mean it's really new! – will Jul 24 '15 at 13:30
  • @will some level of duplication is unavoidable on SO, your received two upvotes so that indicates it was a good question, it just was answered already. – Shafik Yaghmour Jul 24 '15 at 18:52

1 Answers1

6

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.

Alexander Balabin
  • 2,055
  • 11
  • 13