How to immediately invoke a C++ lambda?

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.

Leave a Comment