1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
bf(C++) supports hi(lambda expression) em(lambda expressions). As we'll see in
chapter ref(GENERIC) em(generic algorithms) often accept arguments that can
either be function objects or plain functions. Examples are the tt(sort)
(cf. section ref(SORT)) and tt(find_if) (cf. section ref(FIND)) generic
algorithms. As a i(rule of thumb): when a called function must remember its
state a function object is appropriate, otherwise a plain function can be
used.
Frequently the function or function object is not readily available, and it
must be defined in or near the location where it is used. This is commonly
realized by defining a class or function in the anonymous namespace (say:
class or function A), passing an A to the code needing A. If that code is
itself a member function of the class B, then A's implementation might benefit
from having access to the members of class B.
This scheme usually results in a significant amount of code (defining the
class), or it results in complex code (to make available software elements
that aren't automatically accessible to A's code). It may also result in code
that is irrelevant at the current level of specification. Nested classes don't
solve these problems either. Moreover, nested classes can't be used in
templates.
lambda expressions solve these problems. A i(lambda expression) defines an
i(anonymous function object) which may immediately be passed to functions
expecting function object arguments, as explained in the next few sections.
According to the C++ standard, lambda expressions em(provide a concise way to
create simple function objects.) The emphasis here is on em(simple): a lambda
expression's size should be comparable to the size of inline-functions: just
one or maybe two statements. If you need more code, then encapsulate that code
in a separate function which is then called from inside the lambda
expression's compound statement, or consider designing a separate function
object.
|