我如何创建一个lambda函数来匹配boost::函数参数,而不使用c++ 0x

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

本文关键字:函数 参数 c++ 0x boost 创建 何创建 lambda 一个      更新时间:2023-10-16

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

#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 */);
}

我不能使用c++ 0x,并且希望避免创建几个单独的函数。如果有帮助,我可以使用boost::function以外的东西,我的优先级是简洁地创建lambda。

#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);

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

提振。Lambda严格用于定义具有类似c++语法的内联函数,而Boost。Phoenix是一种建立在c++之上的函数式编程语言,它滥用了c++的语法和编译时计算能力。提振。凤凰号比Boost要强大得多。

简短的回答:no.

c++ 0x lambdas的发明正是为了做你想做的事情。它们实际上只不过是在下面的示例中使Increment匿名/内联的一种方式。这是在任何标准c++中获得匿名函数的惟一方法。

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
}

lambda的唯一神奇之处在于它们的类型不能拼写,但编译器可以将内部隐藏类型绑定到std::function(甚至在某些情况下是C函数指针)。

我张贴上面的代码,因为我认为你的问题可能并不意味着你认为它做什么。 lambda 绝对是c++ 0x的东西,但在本例中,Increment闭包。(有些人会说,只有当你返回它,并且绑定的变量逃离了它被绑定的上下文时,它才会成为闭包——这是吹毛求疵,但这就是Javascript所做的)。

你的问题是关于lambda还是闭包?