Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to immediately invoke a C++ lambda?

Tags:

A constructor from a class I'm inheriting requires a non-trivial object to be passed in. Similar to this:

MyFoo::MyFoo() : SomeBase( complexstuff ) {     return; } 

The complexstuff has little to do with MyFoo, so I didn't want to have to pass it in.

Instead of writing some kind of 1-off temporary function that returns complexstuff I used a lambda. What took me a few minutes to figure out is I have to invoke the lambda. So my code now looks like this:

MyFoo::MyFoo() : SomeBase(     []()     {         /* blah blah do stuff with complexstuff */         return complexstuff;     } () ) {     return; } 

If you didn't catch it, it is subtle. But after the lambda body, I had to put () to tell the compiler to immediately "run" the lambda. Which made sense after I figured out what I had done wrong. Otherwise, without the () to invoke the lambda, gcc says something similar to this:

error: no matching function for call to 'SomeBase(<lambda()>)' 

But now that has me thinking -- did I do this correctly? Is there a better way in C++11 or C++14 to tell the compiler that I want it to immediately invoke a lambda I've written? Or is appending an empty () like I did the usual way to do this?

like image 665
Stéphane Avatar asked Jul 02 '17 07:07

Stéphane


People also ask

Can lambda function be immediately invoked?

You can invoke Lambda functions directly using the Lambda console, a function URL HTTP(S) endpoint, the Lambda API, an AWS SDK, the AWS Command Line Interface (AWS CLI), and AWS toolkits.

How do you call a lambda in C++?

A lambda is also just a function object, so you need to have a () to call it, there is no way around it (except of course some function that invokes the lambda like std::invoke ). If you want you can drop the () after the capture list, because your lambda doesn't take any parameters.


1 Answers

But now that has me thinking -- did I do this correctly?

Yes you did.

Is there a better way in C++11 or C++14 to tell the compiler that I want it to immediately invoke a lambda I've written?

Not that I know of. A lambda is also just a function object, so you need to have a () to call it, there is no way around it (except of course some function that invokes the lambda like std::invoke).

If you want you can drop the () after the capture list, because your lambda doesn't take any parameters.

Or is appending an empty () like I did the usual way to do this?

Yes, it is the shortest way. As said before, std::invoke would also work instead, but it requires more typing. I would say a direct call with () is the usual way it is done.

like image 186
Rakete1111 Avatar answered Oct 23 '22 15:10

Rakete1111