Assigning lambdas to std::functions

As mentioned earlier, every lambda function has its own type, and therefore cannot be assigned to other lambda functions, even if they look exactly the same. However, a std::function can hold any lambda function which has the same signature, that is, it has the same parameters and the same return value. A std::function can also be reassigned at run time. This makes std::function the type to use if you want a variable to hold a lambda function.

What is important here is that what is captured by the lambda does not affect its signature, and therefore both lambdas with and without captures can be assigned to the same std::function.

The following code block shows how different lambdas are assigned the same ...

Get C++ High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.