C++ 中的 Lambda 表达式与函子

2021-12-23 00:00:00 lambda c++

我想知道在 C++ 中我们应该在哪里使用 lambda 表达式而不是函子.对我来说,这两种技术基本相同,甚至 functor 也比 lambda 更优雅、更简洁.例如,如果我想重用我的谓词,我必须一遍又一遍地复制 lambda 部分.那么 lambda 什么时候真正到位?

I wonder where should we use lambda expression over functor in C++. To me, these two techniques are basically the same, even functor is more elegant and cleaner than lambda. For example, if I want to reuse my predicate, I have to copy the lambda part over and over. So when does lambda really come in to place?

推荐答案

1) 它是微不足道的,试图分享它更多的是工作而不是利益.

1) It's trivial and trying to share it is more work than benefit.

2) 定义函子只会增加复杂性(因为必须创建一堆成员变量和废话).

2) Defining a functor simply adds complexity (due to having to make a bunch of member variables and crap).

如果这些都不是真的,那么也许你应该考虑定义一个函子.

If neither of those things is true then maybe you should think about defining a functor.

您似乎需要一个示例,说明何时在函子上使用 lambda 会更好.给你:

it seems to be that you need an example of when it would be nice to use a lambda over a functor. Here you go:

typedef std::vector< std::pair<int,std::string> > whatsit_t;

int find_it(std::string value, whatsit_t const& stuff)
{
  auto fit = std::find_if(stuff.begin(), stuff.end(), [value](whatsit_t::value_type const& vt) -> bool { return vt.second == value; });

  if (fit == stuff.end()) throw std::wtf_error();

  return fit->first;
}

如果没有 lambdas,您将不得不使用类似的东西在现场构造一个函子,或者为一些烦人的琐碎事情编写一个外部可链接的函子对象.

Without lambdas you'd have to use something that similarly constructs a functor on the spot or write an externally linkable functor object for something that's annoyingly trivial.

顺便说一句,我想也许 wtf_error 是一个扩展.

BTW, I think maybe wtf_error is an extension.

相关文章