ptr_fun()函数比前面两个函数就要简单多了,这个函数只是将一个一般形式调用的函数(语法#1调用)包装成为一个可被适配的函数。还记得在条款40中,我们知道一个可适配的仿函数类必须从unary_function或binary_function继承。ptr_fun的功能就是包装一个一般意义的函数,生成一个可适配的仿函数对象。
// TEMPLATE FUNCTION ptr_fun
template<class _Arg,class _Result> inline
pointer_to_unary_function<_Arg, _Result, _Result (__cdecl *)(_Arg)>//返回类型
ptr_fun(_Result (__cdecl *_Left)(_Arg))
{ // return pointer_to_unary_function functor adapter
return (std::pointer_to_unary_function<_Arg, _Result, _Result (__cdecl *)(_Arg)>(_Left));
}

pointer_to_unary_function类:
// TEMPLATE CLASS pointer_to_unary_function
template<class _Arg,class _Result,class _Fn = _Result (*)(_Arg)>
class pointer_to_unary_function: //仿函数类的定义,继承自unary_function
public unary_function<_Arg, _Result>
{ // functor adapter (*pfunc)(left)
public:
explicit pointer_to_unary_function(_Fn _Left): _Pfun(_Left)
{ // construct from pointer
}
_Result operator()(_Arg _Left) const
{ // call function with operand
return (_Pfun(_Left));//转换成实际的调用
}
protected:
_Fn _Pfun; // the function pointer
};
not1(test);//错误,not1需要一个可适配的函数参数,而test不是
not1(ptr_fun(test));//OK,test函数用ptr_fun包装返回可适配的仿函数类满足not1要求
总结:
ptr_fun函数只是简单的对实际函数进行包装,其真实目的只是定义适配器需要的typedef,一个ptr_fun有关的可选策略是只有当你被迫时才使用它。如果当typedef是必要时你忽略了它,你的编译器将退回你的代码。然后你得返回去添加它。
mem_fun和mem_fun_ref的情况则完全不同。只要你传一个成员函数给STL组件,你就必须使用它们,因为,除了增加typedef(可能是或可能不是必须的)之外,它们把调用语法从一个通常用于成员函数的适配到在STL中到处使用的。当传递成员函数指针时如果你不使用它们,你的代码将永远不能编译。