Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type conversion for lambda C++

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?

like image 390
Oleg Avatar asked Jan 03 '23 10:01

Oleg


2 Answers

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).

like image 146
Kerrek SB Avatar answered Jan 08 '23 11:01

Kerrek SB


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]

like image 43
alain Avatar answered Jan 08 '23 10:01

alain