【C++】std::bind和std::placeholders
std::bind
是C++11引入的函数适配器模板,用于创建新的可调用对象,其核心语法和功能如下
#include <functional>
auto new_callable = std::bind(callable, arg_list);
callable
:可绑定对象(函数、成员函数、函数对象、lambda等)-
arg_list
:参数列表,支持混合固定值和占位符std::placeholders::_N
2. 参数绑定规则
- 固定值绑定:直接传递值或对象,调用时无需再指定
auto bound = std::bind(func, 10, 20); // 绑定两个固定参数 bound(); // 等价于 func(10, 20)
占位符绑定:通过
std::placeholders::_1
、_2
等动态指定参数位置auto bound = std::bind(func, _1, _2); // 调用时需传入两个参数 bound(30, 40); // 等价于 func(30, 40)
3. 成员函数绑定
需显式传递对象指针或引用,并指定占位符
class MyClass { public:void method(int x) { /*...*/ } }; MyClass obj; auto bound = std::bind(&MyClass::method, &obj, _1); // 绑定对象和成员函数 bound(42); // 等价于 obj.method(42)
4. 参数重排与适配
通过占位符调整参数顺序
void connect(string ip, int port); auto reversed = std::bind(connect, _2, _1); // 参数顺序反转 reversed(8080, "127.0.0.1"); // 等价于 connect("127.0.0.1", 8080)
5. 引用参数绑定
使用
std::ref
避免拷贝void update(int& val); int x = 0; auto bound = std::bind(update, std::ref(x)); // 绑定引用 bound(); // x会被修改
6. 返回值类型(可选)
通过模板参数指定返回类型(需C++17起支持)
auto bound = std::bind<int>(func, _1); // 显式指定返回int类型
注意事项
- 性能:相比直接调用或lambda有额外开销
- 可读性:复杂绑定逻辑可能降低代码可读性,推荐优先使用lambda
- 类型安全:需确保调用时参数匹配绑定签名