
在C++中,std::bind 是一个非常实用的函数适配器,它能够将可调用对象(如函数、函数指针、成员函数、lambda表达式等)与其参数进行绑定,生成一个新的可调用对象。这个功能在需要延迟调用或部分参数预先设定的场景中特别有用。
#include
std::bind(callable, arg1, arg2, ...)
using namespace std::placeholders;
立即学习“C++免费学习笔记(深入)”;
int add(int a, int b) {
return a + b;
}
我们可以使用 bind 将其中一个参数固定:auto add_10 = std::bind(add, 10, _1); // 固定第一个参数为10 int result = add_10(5); // 相当于 add(10, 5),结果为15这里 _1 表示调用时传入的第一个参数。你也可以交换顺序:
auto add_last_10 = std::bind(add, _1, 10);
class Calculator {
public:
int multiply(int x) {
return value * x;
}
private:
int value = 5;
};
Calculator calc;
auto mul_by_calc = std::bind(&Calculator::multiply, &calc, _1);
int res = mul_by_calc(3); // 调用 calc.multiply(3),结果为15
注意:#include这里将阈值 limit 绑定到函数,生成一个一元谓词供 find_if 使用。#include #include bool greater_than(int a, int threshold) { return a > threshold; }
std::vector
nums = {1, 3, 5, 7, 9, 11}; int limit = 6; auto is_greater_6 = std::bind(greater_than, _1, limit); auto it = std::find_if(nums.begin(), nums.end(), is_greater_6);
if (it != nums.end()) { std::cout << "First number > 6 is: " << *it << std::endl; }
上面的例子也可写成:
auto is_greater_6 = [limit](int a) { return a > limit; };
例如,调换参数顺序:
auto sub_reverse = std::bind(subtract, _2, _1);
基本上就这些。std::bind 虽然灵活,但语法略显繁琐。现代 C++ 更推荐优先使用 Lambda,但在需要复用绑定逻辑或处理复杂调用签名时,bind 依然是一个可用工具。