我如何创建一个lambda函数来匹配boost::函数参数,而不使用c++ 0x
How do I create a lambda function to match a boost::function parameter without using C++0x?
如何使用boost或stl创建lambda函数以匹配F
在main
中的第三段代码中期望的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还是闭包?
相关文章:
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 当从函数参数中的临时值调用复制构造函数时
- 如何从"decltype()"获取函数参数的数量<funtion>?
- 如何将lambda作为模板类的成员函数参数
- 模板参数推导失败,函数参数/参数不匹配
- 如何在C++中将迭代器作为函数参数传递
- 将函数参数"const char*"转换为"std::string_view"是
- C++ 如何将数组值解压缩为函数参数
- 主函数参数的属性
- 具有两个间接寻址运算符 (C++) 的函数参数的用途
- "Warning: Comma within array index expression"但逗号分隔函数参数
- 如何定义在用作函数参数时工作的类模板的转换
- 将函数参数完美转发到函数指针:按值传递呢?
- 为什么我不能将引用作为 std::async 的函数参数传递
- 什么..(省略号)作为函数原型中唯一的函数参数,C++?
- 是否可以就地构造一个固定大小的数组作为函数参数?
- 接受模板作为函数参数
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- Arduino 函数参数