Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any other advantage of lambdas besides convenience? [closed]

Tags:

c++

c++11

lambda

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.

like image 364
NPS Avatar asked Dec 03 '22 18:12

NPS


2 Answers

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.

like image 83
Maxim Egorushkin Avatar answered May 19 '23 12:05

Maxim Egorushkin


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.

like image 45
ecatmur Avatar answered May 19 '23 13:05

ecatmur