10

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.

4
  • 8
    See Passing lambda as function pointer ... tl;dr lambda can only be converted to a function pointer if it does not capture. Commented Jul 24, 2015 at 13:11
  • @ShafikYaghmour Yeah you weren't kidding about marking duplicates when you have an answer... Commented Jul 24, 2015 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! Commented Jul 24, 2015 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. Commented Jul 24, 2015 at 18:52

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.