4

Is it possible to pass a lambda function as a function of some type?

For example, I have

typedef double(*Function)(int, double);

How can I convert a lambda function to the type?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Oleg
  • 43
  • 4

2 Answers2

7

For a stateless lambda, this conversion is available implicitly:

Function f = [](int, double) -> double {};

If you just want to convert the lambda expression itself, you can use the unary + operator to achieve this:

auto* p = +[](int, double) -> double {};   // p is of type double(*)(int, double)

A lambda with a capture offers no such conversion, since it is not semantically equivalent to a (stateless) function (this applies even to the case of a default capture that doesn't end up capturing anything).

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • _"unary + operator"_ That's great! (As mentioned [here](https://stackoverflow.com/questions/46283731/a-function-definition-is-not-allowed-here-before-token#comment79533605_46283731) there are still white spots to explore on the maps). – user0042 Sep 18 '17 at 18:16
  • 1
    @user0042 - It is great. But sadly, a certain mainstream compiler, that shall remain unnamed, [still chokes on it](http://rextester.com/BQND42154). – StoryTeller - Unslander Monica Sep 18 '17 at 18:27
  • 1
    See https://stackoverflow.com/a/17822241/801894 for a deeper explanation of the unary + option. – Solomon Slow Sep 18 '17 at 19:22
2

You could use std::function instead of a plain function pointer. This would allow to hold lambdas even when they have captures:

#include <iostream>
#include <functional>

typedef std::function<double(int, double)> Function;

int main()
{
    Function f;
    int i = 4;
    f = [=](int l, double d){ return i*l*d; };
    std::cout << f(2, 3);
}

[Live Demo]

alain
  • 11,939
  • 2
  • 31
  • 51