std::bind是C++11引入的函数适配器,用于预设函数参数生成可调用对象;支持绑定普通函数、成员函数及参数重排,常用于回调和STL算法,但性能敏感时推荐lambda或C++17的std::bind_front。
std::bind 是 C++11 引入的函数适配器,用来“预设”函数的某些参数,生成一个可调用对象(callable object),后续再用剩余参数调用它。它不是必须的(lambda 往往更简洁),但在需要延迟绑定、复用固定参数或适配接口时很实用。
假设有一个加法函数:
int add(int a, int b) { return a + b; }用 std::bind 把第一个参数固定为 10,得到一个“加 10”的新函数:
auto add10 = std::bind(add, 10, std::placeholders::_1);这里 std::placeholders::_1 表示将来调用时传入的第一个参数(即原函数的第二个参数)。之后可以这样用:
int result = add10(5); // 相当于 add(10, 5),结果是 15占位符 _1、_2、_3… 按顺序对应调用时传入的参数位置,不一定要按原函数顺序写,还能重排:
auto sub_b_a = std::bind(subtract, std::placeholders::_2, std::placeholders::_1); // 交换参数顺序对类成员函数,第一个参数必须是对象上下文(this):
struct Calculator { int multiply(int x, int y) { return x * y; } };也可以绑定到智能指针或 this(在成员函数内):
std::bind(&Calculator::multiply, this, std::placeholders::_1, 5)常见于回调、STL 算法或事件处理中。例如用 std::find_if 找大于某阈值的数:
std::vector等价于 lambda:[threshold](int x) { return x > threshold; },但 bind 更显式表达“把 threshold 绑定进去”这个动作。