将Lambda表达式分配给变量在C++中是一个良好的实践吗?

huangapple go评论60阅读模式
英文:

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

问题

在C++中,将lambda表达式分配给变量是否被视为良好的做法?我知道从Python来看,这并不是一个好的实践。在C++中,将lambda表达式分配给变量的做法在某些情况下被认为是方便定义functors的一种方式。

英文:

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

https://stackoverflow.com/questions/134626/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

https://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11

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.

答案1

得分: 2

总的来说,通常是的。它通过使代码更易读来改进代码。当然,不要仅仅为了使用 lambda 而使用 lambda。

英文:

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.

huangapple
  • 本文由 发表于 2023年4月13日 22:11:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76006448.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定