std::bind 用于绑定可调用对象与参数,生成新函数对象。例如 auto add_5 = std::bind(add, 5, std::placeholders::_1); 固定第一个参数为5,后续调用只需传入第二个参数。

在C++中,std::bind 是一个函数模板,用于将可调用对象(如函数、成员函数、lambda表达式等)与其参数进行绑定,生成一个新的可调用对象。它常用于延迟调用、参数预设或适配函数签名。配合 std::function 使用,可以更灵活地处理回调和事件机制。
auto bound_func = std::bind(callable, arg1, arg2, ...);
其中,占位符 _1, _2, ... 来自
int add(int a, int b) { return a + b; }
立即学习“C++免费学习笔记(深入)”;
我们可以用 std::bind 固定其中一个参数:auto add_5 = std::bind(add, 5, std::placeholders::_1);
此时 add_5 是一个接受一个参数的函数对象,相当于 add(5, x):std::cout
class Calculator {
public:
int multiply(int x) { return value * x; }
private:
int value = 10;
};
Calculator calc;
auto mul_by_calc = std::bind(&Calculator::multiply, &calc, std::placeholders::_1);
std::cout
#include <functional>
std::function<int(int)> func = std::bind(add, 5, std::placeholders::_1);
std::vector<std::function<int(int)>> operations;
operations.push_back(func);
operations.push_back(std::bind(add, std::placeholders::_1, 2));
auto sub_reverse = std::bind(add, std::placeholders::_2, std::placeholders::_1);
调用 sub_reverse(10, 3) 实际执行 add(3, 10),结果为 13。auto lambda = [](const std::string& s, int n) { return s + ":" + std::to_string(n); };
auto greet = std::bind(lambda, std::placeholders::_1, 100);
std::cout
基本上就这些。std::bind 虽然功能强大,但 C++11 之后 lambda 更简洁,多数场景推荐优先使用 lambda。但在需要动态绑定或回调注册时,std::bind 依然有其价值。
以上就是c++++中std::bind怎么使用_c++函数绑定器用法示例的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号