The usefulness of the lambda library is manifested by the fact that it was used for implementing other TR1 libraries. However, such interdependencies among new libraries make learning one library at a time more difficult. In your opinion, is this an acceptable tradeoff or would you rather make changes to core C++ to facilitate the implementation of lambda constructs? Let us know in our C++ Forum.
Creating Unnamed Functions with the Lambda Library (cont'd)
Lambda by Numbers
A unary expression uses one placeholderthe predefined variable _1. The lambda library defines two more placeholders: _2 and _3 for binary and ternary functors, respectively. These placeholders are useful for creating an unnamed function taking two and three operands, respectively. Let's look at an example.
Suppose you have a container of pointers that needs to be sorted. The default sort() implementation will sort the bare pointers, which isn't what you usually want. To override this behavior, provide a lambda functor as the third argument:
Let's see how it works. vp[n] is a pointer. Hence, the placeholders _1 and _2 represent pointers. The complete lambda expression dereferences these pointers and returns a Boolean value indicating whether *_1 is less than *_2. This binary lambda functor ensures that the sorting operation produces the desired results.
Lambda Unlimited
The lambda library has many other constructs for defining if-then-else statements, exception handling, switch statements and the sizeof and typeid operators. Although you've only seen the basic features of the lambda library here, it's clear that it's a very powerful addition to the C++ Standard Library.
Danny Kalev is a certified system analyst and software engineer specializing in C++ and theoretical aspects of formal languages. He was a member of the C++ standards committee between 1997 and 2000. He recently finished his MA in general linguistics summa cum laude. In his spare time he likes to listen to classical music, read Victorian literature and explore natural languages such as Hittite, Basque and Irish Gaelic. Additional interests include archeology and geology. Danny moderates several C++ forums and contributes regularly to various C++-related sites and magazines. He also gives lectures about programming languages and applied linguistics at academic institutes.