1.作用
bind
可以看做一个函数适配器,它接受一个可调用对象,生成一个新的可调用对象来适应原对象的参数列表。
2.语法
auto newCallable = bind(callable, arg_list);
arg_list
是一个逗号分割的参数列表,对应给定的callable
参数。当我们调用newCallable
时,newCallable
会调用callable
并传递给它arg_list
中的参数。
bool check_size(const string& str, int sz){
return str.size() >= sz;
}
auto newCallable = bind(check_size, placeholders::_1, 6);
cout << newCallable("hello world") << endl;//output:1
3.使用注意事项
- 使用
bind
重排参数顺序。
bool is_shorter(const string& str1, const string& str2){
return str1.size() < str2.size();
}
auto newCallable = bind(is_shorter, placeholders::_2, placeholders::_1);
//is_shorter(a, b) 等效于 newCallable(b, a)
- 值绑定与引用绑定
值绑定
int i = 5;
auto newCallable = bind(check_size, placeholders::_1, i));
cout << newCallable("hello world") << endl;//1
i = 20;
cout << newCallable("hello world") << endl;//1
引用绑定
int i = 5;
auto newCallable = bind(check_size, placeholders::_1, ref(i));
cout << newCallable("hello world") << endl;//1
i = 20;
cout << newCallable("hello world") << endl;//1