所谓函数适配器,也就是将一个仿函数或者另一个仿函数(或者数值)结合成新的仿函数。它声明与
<functional>中,如以下的定义find_if (coll.begin(),coll.end(),bind2nd(greater<int>(),42));
常用的预定义的函数适配器如下:
bindlst(op,value) //其实它和下面的bind2nd,都是把op是二元仿函数转成一元仿函数,value作为一元仿函数的参数。
bind2nd(op,value)
not1(op)
not2(op)
如以下:
pos=find_if(coll.begin(),coll.end(),not1(bind2nd(modulus<int>,2)));
这其中的bind2nd,就是将容器中的每一元素取模运算。然后要是奇数则应该返回1,1为真,则not1即为假,所以是找coll容器中的第一个偶数值。
针对函数成员变量而设的函数适配器。
mem_fun_ref(op)
mem_fun(op)
如以下:
//成员函数适配器
class PersonFunctor
{
private:
std::string name;
public:
PersonFunctor(string valueName):name(valueName)
{
}
//成员函数一,打印名称。
void print() const //定义const类型
{
std::cout<<name<<std::endl;
}
//成员函数二,带前缀的打印名称。
void printWithPrefix(std::string prefix) const
{
std::cout<<prefix<<name<<std::endl;
}
};
成员函数适配器定义如下。
//成员函数适配器
void foo(const std::vector<PersonFunctor>& coll)
{
using std::for_each;
using std::bind2nd;
using std::mem_fun_ref;
//mem_fun_ref只能调用参数等于1个或者无参数的成员变量,因为要是有几个参数,就会产生大量的仿函数。
for_each(coll.begin(),coll.end(),mem_fun_ref(&PersonFunctor::print));
//为成员函数传递一个参数
for_each(coll.begin(),coll.end(),bind2nd(mem_fun_ref(&PersonFunctor::printWithPrefix),"Person:"));
}
调用的验证代码如下:
cout<<"----------function adapter-------"<<endl;
vector<PersonFunctor> personVector;
PersonFunctor person1("Gavin"),person2("Liu"),person3("Gao"),person4("LG"),person5("GL");
personVector.push_back(person1);
personVector.push_back(person2);
personVector.push_back(person3);
personVector.push_back(person4);
personVector.push_back(person5);
foo(personVector);
结果如下: