如何在不使用C++ 0x的情况下创建lambda函数来匹配boost :: function参数?

Pet*_*McG 5 c++ boost stl

如何使用boost或stl创建lambda函数以匹配第三段代码中的boost::function预期参数?Fmain

#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 */);
}
Run Code Online (Sandbox Code Playgroud)

我不能使用C++ 0x,并希望避免创建几个单独的函数.我可以使用其他东西,boost::function如果这有帮助,我的优先事项是简洁地创建lambda.

ken*_*ytm 7

#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);
Run Code Online (Sandbox Code Playgroud)

您可能需要添加一些using namespace来简化代码.

Boost.Lambda严格用于使用类似C++的语法定义函子,而Boost.Phoenix是一种基于C++构建的函数式编程语言,它滥用(☺)它的语法和编译时计算能力.Boost.Phoenix比Boost.Lambda强大得多,但前者也需要更多的时间来编译.