转自:http://www.cplusplus.com/reference/std/functional/ptr_fun/
template <class Arg, class Result> pointer_to_unary_function<Arg,Result> ptr_fun (Result (*f)(Arg)); template <class Arg1, class Arg2, class Result> pointer_to_binary_function<Arg1,Arg2,Result> ptr_fun (Result (*f)(Arg1,Arg2));
template <class Arg, class Result> pointer_to_unary_function<Arg,Result> ptr_fun (Result (*f)(Arg)) { return pointer_to_unary_function<Arg,Result>(f); } template <class Arg1, class Arg2, class Result> pointer_to_binary_function<Arg1,Arg2,Result> ptr_fun (Result (*f)(Arg1,Arg2)) { return pointer_to_binary_function<Arg1,Arg2,Result>(f); }
// ptr_fun example #include <iostream> #include <functional> #include <algorithm> #include <cstdlib> #include <numeric> using namespace std; int main () { char* foo[] = {"10","20","30","40","50"}; int bar[5]; int sum; transform (foo, foo+5, bar, ptr_fun(atoi) ); sum = accumulate (bar, bar+5, 0); cout << "sum = " << sum << endl; return 0; }
sum = 150
// ceshi1.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <functional> using std::cout; using std::endl; /* binary_function */ template<typename Arg1,typename Arg2,typename Ret> class binary_function{ public: typedef Arg1 first_argument_type; typedef Arg2 second_argument_type; typedef Ret return_type; }; /* pointer_to_binary_function */ template<typename Arg1,typename Arg2,typename Ret> class pointer_to_binary_function:public binary_function<Arg1,Arg2,Ret>{ private: Ret (*pmf)(Arg1,Arg2); public: explicit pointer_to_binary_function(Ret (*pmf_)(Arg1,Arg2)) :pmf(pmf_){ } Ret operator()(Arg1 left,Arg2 right){ return pmf(left,right); } }; /* ptr_fun */ template<typename Arg1,typename Arg2,typename Ret> pointer_to_binary_function<Arg1,Arg2,Ret> ptr_fun(Ret (*pf)(Arg1,Arg2)){ return pointer_to_binary_function<Arg1,Arg2,Ret>(pf); } /* test_function */ void test_function(int a,int b){ cout<<"Arg1 is "<<a<<endl; cout<<"Arg2 is "<<b<<endl; } /* main */ int main(int argc,char* argv[]){ int a=3; int b=30; (pointer_to_binary_function<int,int,void>(test_function))(a,b); return 0; }