mem_fun mem_fun_ref

本文介绍如何使用mem_fun和mem_fun_ref绑定类成员函数到STL算法中,如for_each。阐述了两者之间的区别及应用场景,并通过具体示例进行说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值