Search code examples
c++lambdafunctor

It is Good Practice to Assign Lambda Expression to a Variable in C++?


Is it considered as good practice to assign lambda expressions in C++ to a variable? I know from python, that it isn't good practice

Which is more preferable to use: lambda functions or nested functions ('def')?

which makes perfect sense to me, because it makes no sense to give an anonymous function a name. However, I have seen very often in C++ that lambda is assigned to a variable, like here for example

https://en.cppreference.com/w/cpp/language/lambda https://en.cppreference.com/w/cpp/ranges/drop_view

Is this considered as good practice in C++? From this post here

What is a lambda expression in C++11?

I conclude, it can be also seen as very convenient way to define functors. So it looks like lambda is in C++ considered as more than just an anonymous function.


Solution

  • In short, it usually is. It improves your code by making it more readable. Of course, don't use lambda for lambda's own sake.