Chapter 43. Boost.Lambda

    The purpose of lambda functions is to make code more compact and easier to understand (see Example 43.1).

    Example 43.1. with a lambda function

    boost::lambda::_1 is a placeholder that creates a lambda function that expects one parameter. The number in the placeholder determines the number of expected parameters, so boost::lambda::_2 expects two parameters and boost::lambda::_3 expects three parameters. Boost.Lambda only provides these three placeholders. The lambda function in uses boost::lambda::_1 because std::for_each() expects a unary function.

    Include boost/lambda/lambda.hpp to use placeholders.

    Example 43.2. A lambda function with

    1. #include <boost/lambda/lambda.hpp>
    2. #include <boost/lambda/if.hpp>
    3. #include <vector>
    4. #include <iostream>
    5. int main()
    6. std::vector<int> v{1, 3, 2};
    7. boost::lambda::if_then(boost::lambda::_1 > 1,
    8. }

    The header file boost/lambda/if.hpp defines constructs you can use to create if control structures in a lambda function. The simplest construct is the function template boost::lambda::if_then(), which expects two parameters: the first parameter is a condition. If the condition is true, the second parameter is executed. Both parameters can be lambda functions, as in Example 43.2.