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 表示将来调用时传入的第一个参数(即原函数的第二个参数)。之后可以这样用:
立即学习“C++免费学习笔记(深入)”;
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; } };Calculator calc;
auto times2 = std::bind(&Calculator::multiply, &calc, std::placeholders::_1, 2);
int r = times2(7); // 调用 calc.multiply(7, 2) → 14
也可以绑定到智能指针或 this(在成员函数内):
std::bind(&Calculator::multiply, this, std::placeholders::_1, 5)绑定部分参数 + 延迟求值场景
常见于回调、STL 算法或事件处理中。例如用 std::find_if 找大于某阈值的数:
std::vectorint threshold = 6;
auto is_greater = std::bind(std::greater
auto it = std::find_if(v.begin(), v.end(), is_greater); // 找第一个 >6 的元素
等价于 lambda:[threshold](int x) { return x > threshold; },但 bind 更显式表达“把 threshold 绑定进去”这个动作。
注意事项和替代建议
- 头文件需包含
- 占位符定义在 std::placeholders 命名空间,常用的是 _1, _2…,别漏了 using namespace std::placeholders; 或写全名
- bind 返回的对象有开销(类型擦除、拷贝捕获),性能敏感时优先考虑 lambda
- C++17 后 std::bind_front 更轻量,只支持前缀绑定(从左往右填参),无占位符,推荐新代码优先用它











