场景需求
查找存储字符的容器中,第一个长度>=sz的元素:
std::vector<string> words; // 字符容器decltype(words.size()) sz = 6; // 第一个长度>=sz的元素bool check_size(const string& a, const decltype(words.size())& sz){return a.size() >= sz;}// 调用adapter(param1)时,等价于调用check_size(param1, sz)auto adapter = std::bind(check_size, _1, sz);auto target = find_if(words.begin(), words.end(), adapter);
可以看出,std::bind是一个函数适配器,将原函数对象适配成一个不同形参列表的新函数对象。
语法
// std::bind在fucntional头文件中// 函数的适配器auto newCallable = std::bind(callable, arg_list);//// 调用newCallable(args)时,等价于调用callable(arg_list)// args可能包含在arg_list中,借助占位符placeholders//// newCallable: 函数对象,callable的函数适配器// callable: 函数对象// arg_list: callable的形参列表,值传递//
例子
using std::placeholders::_1; // 只使用_1using namespace std::placeholders; // 也可以直接使用全部的_n名字int &ref_a = ref(a); // 返回对象,包含a的引用,int &const int &cref_a = cref(a); // 返回a的引用,const int &// ref、cref定义在functional头文件中。// f、f1是可调用对象。auto f = bind(f1); // f() <==> f1()auto f = bind(f1, a, b); // f() <==> f1(a, b)auto f = bind(f1, ref(a), b); // f() <==> f1(a, b),ref(a)返回a的引用auto f = bind(f1, cref(c), b); // f() <==> f1(c, b),cref(c)返回c的常量引用auto f = bind(f1, _1,b); // f(_1) <==> f1(_1,b)auto f = bind(f1, b, _1); // f(_1) <==> f1(b,_1)auto f = bind(f1, _2, b, _1); // f(_1, _2) <==> f1(_2, b, _1)auto f = bind(f1, _3, b, _1); // f(_1, v2,_3) <==> f1(_3, b, _1)
