Boost logo

Boost :

Subject: [boost] [local] "true" lambdas without C++11 but only on GCC
From: Lorenzo Caminiti (lorcaminiti_at_[hidden])
Date: 2011-11-17 12:06:49


Hello all,

A curiosity: On GCC compilers (but _only_ on GCC compilers) it is
possible to combine Boost.Local and the non-standard GCC "expression
statements" feature to implement lambda functions. In other words, it
is possible to define a Boost.Local closure within a GCC expression
statement:

    std::vector<int> v(3);
    v[0] = 1; v[1] = 2; v[2] = 3;
    int factor = 10;

    std::for_each(v.begin(), v.end(),
        LAMBDA(int x, const bind& factor) {
            std::cout << x * factor << std::endl;
        } LAMBDA_END
    );

This is just a curiosity because it is NOT standard C++03 and it will
ONLY work with GCC compilers.

#include <boost/local/function.hpp>
#include <vector>
#include <algorithm>
#include <iostream>

// WARNING: This macros only work on GCC!!!

#define LAMBDA_WITH_RESULT(result_type, ...) \
    ({ /* open GCC statement expression */ \
        result_type BOOST_LOCAL_FUNCTION_PARAMS(__VA_ARGS__)

#define LAMBDA(...) \
    LAMBDA_WITH_RESULT(void, __VA_ARGS__)

#define LAMBDA_END \
        BOOST_LOCAL_FUNCTION_NAME(BOOST_PP_CAT(lambda, __LINE__)) \
        BOOST_PP_CAT(lambda, __LINE__); \
    }) /* close GCC statement expression */

int main() {
    std::vector<int> v(3);
    v[0] = 1; v[1] = 2; v[2] = 3;
    int factor = 10;

    std::for_each(v.begin(), v.end(),
        LAMBDA(int x, const bind& factor) {
            std::cout << x * factor << std::endl;
        } LAMBDA_END
    );
    return 0;
}

I might mention this code example as a curiosity in Boost.Local docs,
currently it's not mentioned there.

Thanks.
--Lorenzo


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk