Calling a lambda expression multiple times

I'm trying to use lambda expressions from the new standard and still don't understand them well enough.

Say I have a lambda somewhere in my code, for example. 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 have to use it several times, so the answer β€œjust define it right there” does not work: P So, how can I call this lambda expression later in the code? Should I make a pointer to it and use this pointer? Or is there a better / easier way?

+4
source share
2 answers

You can save the lambda with 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 create or assign a specific type of std::function later, if necessary:

 std::function<float(int,int)> f3 = f1; 
+17
source
 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; 
+14
source

All Articles