Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a lambda expression multiple times

Tags:

c++

c++11

lambda

I'm trying the lambda-expressions from the new standard, and still don't understand them quite well.

Let's say I have a lambda somewhere in my code, e.g. in my main:

int main( int argc, char * argv[])
{
    //some code
    [](int x, int y)->float
    {
        return static_cast<float>(x) / static_cast<float>(y);
    };
    //some more code here
    //<---now I want to use my lambda-expression here
}

Well obviously I might need to use it multiple times, so the answer "just define it right there" doesn't work :P So, how do I call this lambda expression later in the code? Do I have to make a function pointer to it and use that pointer? Or is there a better/easier way?

like image 586
SingerOfTheFall Avatar asked Aug 21 '12 06:08

SingerOfTheFall


2 Answers

You can store the lambda using auto, or assign it to a compatible std::function explicitly:

auto f1 = [](int x, int y)->float{ ..... };
std::function<float(int,int)> f2 = [](int x, int y)->float{ ..... };

float x = f1(3,4);
auto y = f2(5,6);

You can always use f1 or f2 to construct or assign to a specific std::function type later on if necessary:

std::function<float(int,int)> f3 = f1;
like image 176
juanchopanza Avatar answered Oct 11 '22 08:10

juanchopanza


auto lambda = [](int x, int y)->float
    {
        return static_cast<float>(x) / static_cast<float>(y);
    };
// code
// call lambda
std::cout << lambda(1, 2) << std::endl;
like image 29
ForEveR Avatar answered Oct 11 '22 09:10

ForEveR