Conversion Type for C ++ Lambda

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

For example, I have

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

How to convert lambda function to type?

+4
source share
2 answers

You can use std::functionfunctions instead of simple pointers. This would keep lambdas even when they capture:

#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]

+2
source

For a nuclear-free 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)

, ( ) ( , ).

+7

Source: https://habr.com/ru/post/1685904/


All Articles