Boost库学习之boost::bind

发布时间 2023-12-11 15:01:17作者: 纯真丁一郎です

Purpose

boost::bind 是 boost 库中一个很有用的函数模板,它提供了比 std::bind1ststd::bind2nd 更通用更强大的绑定机制。

boost::bind 的主要作用是:

  1. 将函数或函数对象与其参数绑定,生成一个新的可调用对象。

  2. 允许绑定函数的部分参数,生成一个部分应用的函数。

  3. 支持绑定成员函数。

  4. 不对绑定的函数对象有任何要求。

简单来说,通过 boost::bind,你可以在运行时动态创建可调用对象,并且有很大的灵活性去组合和绑定参数。

下面是一些使用boost::bind的例子:

int add(int a, int b) { return a + b;} 

auto add2 = boost::bind(add, 2, _1);
add2(3); // 5

struct A {
    void func(int a, int b); 
};

A a;
auto a_func = boost::bind(&A::func, &a, 95, _1); 
a_func(3); //调用 a.func(95, 3)

bind(add, 2, 3) 会产生一个零元函数,它不接受参数并且返回add(2, 3)。

bind(add, 2, _1)(x)等价于 add(2,x), _1为占位函数并接受所传入的第一个参数。

int f(int a, int b)
{
    return a+b;
}

int g(int a, int b, int c)
{
    return a+b+c;
}

bind(f, _2, _1)(x, y);                 // f(y, x)
bind(g, _1, 9, _1)(x);                 // g(x, 9, x)
bind(g, _3, _3, _3)(x, y, z);          // g(z, z, z)
bind(g, _1, _1, _1)(x, y, z);          // g(x, x, x)

bind可以处理具有两个以上参数的函数,其参数替换机制更为通用。所以 boost::bind 是一个非常强大有用的工具,比 STD 版的 bind 更加通用和灵活。它在函数、lambda、回调等场景中很常用。

Supplement:

std::bind1ststd::bind2nd 都是C++中用来绑定函数的工具。它们的主要区别在于:

std::bind1st : 固定函数的第一个参数,绑定一个值到第一个参数。

std::bind2nd : 固定函数的第二个参数,绑定一个值到第二个参数。

例如:

bool GreaterThan10(int n, int threshold) {
  return n > threshold; 
}

// 用std::bind1st固定第一个参数
auto f1 = std::bind1st(GreaterThan10, 15); 

// 用std::bind2nd固定第二个参数
auto f2 = std::bind2nd(GreaterThan10, 10);

f1(20); // 调用时只需要传入第二个参数 
f2(15); // 调用时只需要传入第一个参数

在这个例子中,f1会把15作为GreaterThan10的第一个参数n,f2会把10作为第二个参数threshold。

简单总结一下区别:

std::bind1st 绑定函数的第一个参数
std::bind2nd 绑定函数的第二个参数