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.

Leave a Comment