1. 针对函数对象的配接器,把一个函数对象转化成另外一个函数对象;比如:bind1st 和 bin2nd 把一个需要两个参数的函数对象转化成只要一个参数的函数对象;这种配接方式,只需要在operetor()中重新调用需要被被转化的函数对象即可实现;
例子:
pos = find_if (col1.begin(), col1.end(),
not1(bind2nd(moduus<int>(,2)) );
2. 把成员函数转化为函数对象:mem_fun_ref, mem_fun
在使用上面的函数配接器之前,需要把一个函数转化为函数对象,对于成员函数,完成这个转化工作的是 mem_fun_ref,注意成员函数隐藏了一个参数,因为它需要一个对象来调用,所以mem_fun_ref需要把这个参数也考虑进参数列表中;mem_fun_ref 只能处理无参或单参的成员函数;mem_fun_ref 调用的成员函数还必须是 const函数;
例子:
class Person {
...
public:
void func1(string s){...}
}
vector<Person> col1;
for_each ( col1.begin(), col1.end(),
bind2nd( mem_fun_ref(&Person::func1), "hello"); //mem_fun_ref 默认第一个参数是类对象
如果col1是 Person* 的容器,而不是Person,那么需要用 mem_fun;
vector<Person*> col2;
for_each ( col2.begin(), col2.end(),
bind2nd( mem_fun(&Person::func1) ) );
3. 把一般函数(非成员函数)转化为函数对象: ptr_fun
4. 让自定义函数对象也可以使用函数配接器
需要继承std::unary_function或者std::binary_function,他们 typedef 了参数和返回值类型;
例子:
5. 函数对象组合
例子:
// 一元 x
compose_f_gx(bind2nd(multiplies<int>(),5),
bind2nd (plus<int>(),10))
compose_f_gx_hx(logical_and<bool>(),
bind2nd(greater<int>(),4),
bind2nd(less<int>(),7))
// 二元 x, y
pos = search (s .begin(), s. end(), //string to search in
sub.begin() ,sub.end() , //substring to search
compose_f _gx_hy(equal_to<int>(), //compar. criterion
ptr_fun(toupper),
ptr_fun(toupper))); // x 来源于s,y 来源于sub