Lambda Expression vs Functor在C ++中 [英] Lambda Expression vs Functor in C++

查看:80
本文介绍了Lambda Expression vs Functor在C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在C ++中我们应该在函子上使用 lambda 表达式。对我来说,这两种技术基本相同,即使函子比 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;
}

如果没有lambda,则必须使用类似的东西来构造函子为烦人的琐事发现或编写外部可链接的仿函数对象。

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.

这篇关于Lambda Expression vs Functor在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆