for_each绑定函数的时候,如果要绑定类的成员函数,就要用上mem_fun和mem_fun_ref
不用我多说,大家应该已经明白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
};