C++:绑定(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) {
    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/

相关文章:

c++ - 在循环缓冲区中存储结构数据

c++ - Boost Regex 提供空白捕获

c++ - 需要帮助解释 ld 链接器错误

c++ - 构造函数在这一行中做什么?

具有删除旧样本能力的 C++ 累加器库

c++ - 通过继承扩展 shared_ptr

javascript - 绑定(bind)方法不起作用

r - R中tcltk tktext中的重写事件

javascript - 使用绑定(bind)原型(prototype)更改 'this' 的范围

c++ - 从基类的 vector 访问继承的类方法