假设有以下两个函数:
#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);
}
这些函数中的每一个都接受两个参数,但可以通过使用 (std/boost)bind
将其转换为仅接受一个参数的可调用对象。类似的东西:
boost::bind(match1, "a test");
boost::bind(match2, 42);
我希望能够从像这样的两个接受一个参数并返回 bool
的函数中获得一个接受两个参数并返回 的 && 的可调用对象 bool
s。参数的类型是任意的。
对于返回 bool
的函数,类似于 operator&&
。
最佳答案
boost::bind
的返回类型重载了operator &&
(以及many others)。所以你可以写
boost::bind(match1, "a test", _1) && boost::bind(match2, 42, _2);
如果你想存储这个值,使用boost::function
.在这种情况下,类型将是
boost::function<bool(const char *, const char *)>
请注意,这不是 boost::bind
的返回类型(未指定),但任何具有正确签名的仿函数都可以转换为 boost::function
.
关于C++:绑定(bind)的结合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2638781/