mem_fun mem_fun_ref 秒速五厘米 2022-09-26 03:51 130阅读 0赞 for\_each绑定函数的时候,如果要绑定类的成员函数,就要用上mem\_fun和mem\_fun\_ref 例子: for\_each(vECS.begin(), vECS.end(), mem\_fun( & ClxECS::DoSomething)); 不用我多说,大家应该已经明白**mem\_fun**是干什么和该怎么用的了。 **mem\_fun\_ref**的作用和用法跟**mem\_fun**一样,唯一的不同就是:**当容器中存放的是对象实体的时候用mem\_fun\_ref,当容器中存放的是对象的指针的时候用mem\_fun。** **template < class \_Result, class \_Ty > inline const\_mem\_fun\_ref\_t<\_Result, \_Ty> mem\_fun\_ref(\_Result (\_Ty::\*\_Pm)() const) \{ // return a const\_mem\_fun\_ref\_t functor adapter return (std::const\_mem\_fun\_ref\_t<\_Result, \_Ty>(\_Pm)); \} // TEMPLATE CLASS const\_mem\_fun\_ref\_t template < class \_Result, class \_Ty > class const\_mem\_fun\_ref\_t : public unary\_function<\_Ty, \_Result> \{ // functor adapter (\*left.\*pfunc)(), const \*pfunc public: explicit const\_mem\_fun\_ref\_t(\_Result (\_Ty::\*\_Pm)() const) : \_Pmemfun(\_Pm) \{ // construct from pointer \} \_Result operator()(const \_Ty &\_Left) const \{ // call function return ((\_Left.\*\_Pmemfun)()); \} private: \_Result (\_Ty::\*\_Pmemfun)() const; // the member function pointer \};** **bind2nd:** **template < class \_Fn2, class \_Ty > inline binder2nd<\_Fn2> bind2nd(const \_Fn2 &\_Func, const \_Ty &\_Right) \{ // return a binder2nd functor adapter typename \_Fn2::second\_argument\_type \_Val(\_Right); return (std::binder2nd<\_Fn2>(\_Func, \_Val)); \}** **template<class \_Fn2> class binder2nd : public unary\_function < typename \_Fn2::first\_argument\_type, typename \_Fn2::result\_type > \{ // functor adapter \_Func(left, stored) public: typedef unary\_function < typename \_Fn2::first\_argument\_type, typename \_Fn2::result\_type > \_Base; typedef typename \_Base::argument\_type argument\_type; typedef typename \_Base::result\_type result\_type; binder2nd(const \_Fn2 &\_Func, const typename \_Fn2::second\_argument\_type &\_Right) : op(\_Func), value(\_Right) \{ // construct from functor and right operand \} result\_type operator()(const argument\_type &\_Left) const \{ // apply functor to operands return (op(\_Left, value)); \} result\_type operator()(argument\_type &\_Left) const \{ // apply functor to operands return (op(\_Left, value)); \} protected: \_Fn2 op; // the functor to apply typename \_Fn2::second\_argument\_type value; // the right operand \};**
还没有评论,来说两句吧...