std::bind
使用总结(C++11)
1. 绑定普通函数
cpp复制编辑int add(int a, int b) { return a + b; }
auto f = std::bind(add, 1, 2);
f(); // => 3
2. 使用占位符 _1
, _2
,调用时传参数
cpp复制编辑using namespace std::placeholders;
auto f = std::bind(add, _1, 10);
f(5); // => 15
3. 绑定类的成员函数(类外)
cpp复制编辑class A {
public:
void say(int x) { std::cout << "x=" << x << std::endl; }
};
A a;
auto f = std::bind(&A::say, &a, 100);
f(); // 输出:x=100
4. 绑定类的成员函数(类内)
cpp复制编辑class A {
public:
A() {
auto f = std::bind(&A::say, this, 100);
f(); // 输出:x=100
}
void say(int x) { std::cout << "x=" << x << std::endl; }
};
5. 占位符结合成员函数
cpp复制编辑auto f = std::bind(&A::say, &a, _1);
f(42); // 输出:x=42
小结
- 普通函数直接绑定或配合占位符
- 成员函数必须提供对象(
this
或 &obj
) - 占位符
_1
, _2
表示延后传参