C++11 lambdas

Hi all,

Is there any advantage of C++11 lambdas over the normal functions?
And am I advised to use lambdas anytime I want instead of functions(except in structures like classes, structs,...)?

Aceix.
Last edited on
If you need a one time function that you most likely won't use again use a lambda. If you plan on using that function in more then one place make a full fledged function.

As for benefits it makes the code easier to understand (You don't have to jump around the project to see the definition of a one time function all the time) and easier to write simple throw away functions.
Last edited on
It is useful for most functions found in the standard library which require a predicate as argument. If you don't wish to declare a separate one just to use that function, you can instead choose to pass a lambda function to it.

Example

1
2
3
4
5
6
string upper_words = "ABCDEFGHI";

//convert the string to lower_case
for_each(upper_words.begin(), upper_words.end(), [](char &c) {
    c = static_cast<char>(c | 0x20);
});


And the point @EndlessCode made is very important too. It adds readability to your code especially if the "one-time" function is declared in a separate file
Last edited on
Is there any advantage of C++11 lambdas over the normal functions?

I wouldn't compare them to functions. Lambda expressions are an alternative to C++98 function objects, especially stateful function objects. It gets more than a little annoying having to write a lot of them C++98 style (each is separate class with an overloaded function-call operator, often with with data members and a constructor)

In those cases where a pointer to function can work just as well, the only potential benefit of a lambda I can think of is that it's automatically inline (while inlining through a function pointer also happens where possible, it's a slightly more involved optimization)

And am I advised to use lambdas anytime I want instead of functions(except in structures like classes, structs,...)?

instead of simple one-off functions with internal linkage written just to obtain a pointer to pass to an algorithm, sure.
Topic archived. No new replies allowed.