C++ C++;:绑定的连接?
假设以下两个函数:C++ C++;:绑定的连接?,c++,boost,bind,C++,Boost,Bind,假设以下两个函数: #include <iostream> #include <cstdlib> // atoi #include <cstring> // strcmp #include <boost/bind.hpp> bool match1(const char* a, const char* b) { return (strcmp(a, b) == 0); } bool match2(int a, const char* b)
#include <iostream>
#include <cstdlib> // atoi
#include <cstring> // strcmp
#include <boost/bind.hpp>
bool match1(const char* a, const char* b) {
return (strcmp(a, b) == 0);
}
bool match2(int a, const char* b) {
return (atoi(b) == a);
}
我希望能够从两个函数中获取一个可调用对象,这两个函数取一个参数并返回bool
,该对象取两个参数并返回bool
s的&&值。参数的类型是任意的
对于返回
bool
的函数,类似于操作符&&
,boost::bind的返回类型重载操作符&
(以及)。这样你就可以写作了
boost::bind(match1, "a test", _1) && boost::bind(match2, 42, _2);
如果要存储此值,请使用。在本例中,类型为
boost::function<bool(const char *, const char *)>
boost::函数
请注意,这不是boost::bind
(未指定)的返回类型,但是任何具有正确签名的函子都可以转换为boost::function
您不想要一个接受一个参数并返回bool的函数吗?Ie等同于match1(“测试”,X)和&match2(42,X)
?或者你真的想要match1(“一个测试”,X)和&match2(42,Y)
?我真的想要一个带两个参数的函数。我能不能有一个返回boost:bind
类型的函数?它可以工作(顺便说一句,为什么\u 1
和\u 2
在全局命名空间中?@Sebastian,因为它更容易使用?(仅供参考,它们位于boost/bind/placeholder.hpp
中定义的未命名命名空间中)@Jesse Beder:Lambda使用boost::Lambda,Phoenix使用boost::spirit命名空间作为占位符,因此不清楚为什么绑定库应该有所不同。@Sebastian,这似乎是一个流行的问题。我在boost邮件列表中发现了这样一个对话:它链接到一张罚单,但看起来没有采取任何措施。而且似乎std::bind
的占位符将位于std::placeholder
中。
boost::function<bool(const char *, const char *)>