boost::bind,boost::mem_fn,std::mem_fun/mem_fun_ref 比较

#include <Windows.h> #include <iostream> #include <vector> #include <algorithm> #include <functional> #include <boost/mem_fn.hpp> #include <boost/bind.hpp> #include <boost/foreach.hpp> #include <boost/shared_ptr.hpp> #define foreach BOOST_FOREACH using namespace std; class CMyClass { public: void Print() { cout<<nData<<" "; } void Print2(const char * szName) { cout<<szName<<":"<<nData<<" "; } int nData; }; int _tmain(int argc, _TCHAR* argv[]) { vector<CMyClass> a(20); foreach(CMyClass & x,a) x.nData=rand()%200; for_each(a.begin(),a.end(),std::mem_fun_ref(&CMyClass::Print));//使用std的 mem_fun_ref cout<<"/r/n-------------------------------/r/n"; for_each(a.begin(),a.end(),boost::mem_fn(&CMyClass::Print));//使用Boost mem_fn cout<<"/r/n-------------------------------/r/n"; for_each(a.begin(),a.end(),boost::bind(&CMyClass::Print,_1));//使用Boost bind cout<<"/r/n-------------------------------/r/n"; //------------------------------------------------------------------------------------------------------- vector<boost::shared_ptr<CMyClass> > b(20); foreach(boost::shared_ptr<CMyClass> & x,b) { x.reset(new CMyClass()); x->nData=rand()%200; } // for_each(b.begin(),b.end(),std::mem_fun(&CMyClass::Print));//使用std的mem_fun,因为是智能指针,所以这将编译不过 // cout<<"/r/n-------------------------------/r/n"; for_each(b.begin(),b.end(),boost::mem_fn(&CMyClass::Print));//使用Boost mem_fn cout<<"/r/n-------------------------------/r/n"; for_each(b.begin(),b.end(),boost::bind(&CMyClass::Print,_1));//使用Boost bind cout<<"/r/n-------------------------------/r/n"; //------------------------------------------------------------------------------------------------------- for_each(a.begin(),a.end(),boost::bind(&CMyClass::Print2,_1,"值"));//使用Boost bind cout<<"/r/n-------------------------------/r/n"; return 0; }

你可能感兴趣的:(each,include,fun)