The title might not be precise but I couldn't think of any brief one that would be. (Feel free to suggest one or edit my question.)
I was wondering if there is any other advantage of using lambda functions other than the fact that that one doesn't have to explicitly define (and write) the whole class definition of a functor or define a separate function to be used (possibly) just once. In other words, are lambdas introduced just for convenience or is there more to them?
Edit: One thing to add to my question. Lambdas allow programmer to write less, do it more conveniently and therefore they are less error-prone. Which in itself is a different thing/reason than just convenience but is associated with it.
See full motivation for lamdas at A proposal to add lambda functions to the C++ standard :
C++ Standard Library algorithms would be much more pleasant to use if C++ had support for lambdas. Lambda functions would let people use C++ Standard Library algorithms in many cases where currently it is easier to write a for loop. Many developers do not use function objects simply because of the syntactic overhead.
Lambdas are largely syntactic sugar, but not entirely. One point about lambdas is that they capture arrays by direct-initialization in subscript order [expr.prim.lambda]:
22 - [...] (For array members, the array elements are direct-initialized in increasing subscript order.) [...]
This is surprisingly difficult to achieve otherwise; it is necessary to construct an index parameter pack using something like std::index_sequence
and the semantics are not quite the same.
Another thing lambdas can do is to capture a (variadic) parameter pack; this cannot be done generically (since structure members cannot be a parameter pack expansion) except via something like std::tuple
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With