How to create a lambda function to match boost :: function parameter without using C ++ 0x?

How to create a lambda function using boost or stl according to the parameter boost::functionexpected Fin the third code fragment in main?

#include <iostream>
#include <boost/function.hpp>

void F(int a, boost::function<bool(int)> f) {
    std::cout << "a = " << a << " f(a) = " << f(a) << std::endl;
}

bool G(int x) {
    return x == 0;
}

int main(int arg, char** argv) {
    // C++0x
    F(123, [](int i) { return i==0; } );

    // Using seperate function
    F(0, &G);

    // How can I do it in place without C++0x
    F(123, /* create a lambda here to match */);
}

I cannot use C ++ 0x and would like to avoid creating several separate functions. I can use something else that boost::function, if that helps, my priority creates a lambda succinctly.

+5
source share
2 answers
#include <functional>    // STL
#include <boost/lambda/lambda.hpp>   // Boost.Lambda
#include <boost/spirit/include/phoenix_core.hpp>     // Boost.Pheonix
#include <boost/spirit/include/phoenix_operator.hpp> // Boost.Pheonix also

...

// Use STL bind without lambdas
F(0, std::bind2nd(std::equal_to<int>(), 0));
F(123, std::bind2nd(std::equal_to<int>(), 0));

// Use Boost.Lambda (boost::lambda::_1 is the variable)
F(0, boost::lambda::_1 == 0);
F(123, boost::lambda::_1 == 0);

// Use Boost.Phoenix
F(0, boost::phoenix::arg_names::arg1 == 0);
F(123, boost::phoenix::arg_names::arg1 == 0);

You might want to add using namespaceto simplify the code.

Boost.Lambda inline ++, Boost.Phoenix - , ++, (☺) . Boost.Phoenix Boost.Lambda, .

+7

: .

++ 0x lambdas , , . , Increment /. ++.

struct Increment {
    int & arg;
    Increment (int a) : arg (a) {}
    void operator () (int & i)
        {arg += i;}
};

void foo (const std :: vector <int> & buffer, int x)
{
    std :: for_each (
        buffer .begin (), buffer .end (),
        Increment (x)); // C++98

    std :: for_each (
        buffer .begin (), buffer .end (),
        [&x] (int & i) {x += i;}); // C++0x
}

, , std::function ( C ).

, , , , . Lambdas ++ 0x, Increment . ( , , , , , - nitpicking, , , , Javascript).

?

-1

All Articles