Lambda Expression vs Functor in C++

A lambda expression creates an nameless functor, it's syntactic sugar.

So you mainly use it if it makes your code look better. That generally would occur if either (a) you aren't going to reuse the functor, or (b) you are going to reuse it, but from code so totally unrelated to the current code that in order to share it you'd basically end up creating my_favourite_two_line_functors.h, and have disparate files depend on it.

Pretty much the same conditions under which you would type any line(s) of code, and not abstract that code block into a function.

That said, with range-for statements in C++0x, there are some places where you would have used a functor before where it might well make your code look better now to write the code as a loop body, not a functor or a lambda.


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

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.

Edit: 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;
}

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.

BTW, I think maybe wtf_error is an extension.

Tags:

C++

Lambda