使仿函数类可适配

四个标准函数适配器(not1、not2、bind1st和bind2nd)都需要存在某些typedef。所以这4个修饰的仿函数必须是可适配的;

使得仿函数成为可适配的方法:仿函数类继承自unary_function或binary_function实现;

注意

1,传给unary_function或binary_function的类型与传给仿函数类的operator()和从那里返回的一样。

struct WidgetNameCompare:

public std::binary_function<Widget,Widget, bool>{

bool operator()(constWidget& lhs, const Widget& rhs) const;

};

2,,仿函数声明为class还是struct纯粹是一个个人风格问题

3,一般来说,传给unary_function或binary_function的非指针类型都去掉了const和引用。

4,当operator()的参数是指针时这个规则变了。

例子:

struct PtrWidgetNameCompare:

public std::binary_function<const Widget*, const Widget*,bool> {

bool operator()(const Widget* lhs, const Widget* rhs) const;

};

什么时候使用ptr_fun:

1,考虑每当你传递一个函数给STL组件时都使用它;

或者只有当你被迫时才使用它。如果当typedef是必要时你忽略了它,你的编译器将退回你的代码。然后你得返回去添加它。

2,没有运行期的惩罚

什么时候使用mem_fun和mem_fun_ref:

只要你传一个成员函数给STL组件,你就必须使用它们

作用:

1,增加typedef(可能是或可能不是必须的)之外,

2,它们把调用语法从一个通常用于成员函数的适配到在STL中到处使用的。

for_each(vw.begin(),vw.end(), test); // 调用#1(可以编译)

for_each(vw.begin(),vw.end(),&Widget::test); // 调用#2(不能编译)

list<Widget*>lpw; // lpw容纳Widget的指针

for_each(lpw.begin(),lpw.end(),

&Widget::test);// 调用#3(也不能编译)

mem_fun适配语法#3到语法1

mem_fun_ref函数适配语法#2到语法#1

3,指针的容器-------mem_fun

对象的容器--------mem_fun_ref



你可能感兴趣的:(使仿函数类可适配)