现在的位置: 首页 > 综合 > 正文

STL之bind1st

2018年02月16日 ⁄ 综合 ⁄ 共 2463字 ⁄ 字号 评论关闭

1.unary_function

即一元函数

在vs2008自带的STL库中,它的定义如下

 

template <class Arg, class Result>
  struct unary_function {
    typedef Arg argument_type;
    typedef Result result_type;
  };

 

为什么叫一元函数呢?看一下它的使用方法就清楚了

struct IsOdd : public unary_function<int,bool>

{
  bool operator() (int number)

  {

      return (number%2==1);

  }
};

 

就是说,unary_function的子类的函数对象只接收一个参数

bool operator() (int number)中的int number

"this operator() member function takes one single parameter"

 

unary_function测试代码如下

 

 

 

2.binary_function

二元函数对象,由上易知这个函数对象有两个参数

见它的定义

template<class _Arg1,
    class _Arg2,
    class _Result>
    struct binary_function
    {    // base class for binary functions
    typedef _Arg1 first_argument_type;
    typedef _Arg2 second_argument_type;
    typedef _Result result_type;
    };

 

“In the case of binary function objects, this operator() member function takes two parameters.”

 

TestBinaryFunc()测试代码如下

 

 

3.bind1st

看完了1和2,bind1st就很容易理解了。它先利用binary_function,先绑定一个

参数,然后像使用一元函数对象那样使用binary_function

 

以下是bind1st的部分代码

  binder1st(const _Fn2& _Func,
        const typename _Fn2::first_argument_type& _Left)
        : op(_Func), value(_Left)
        {    // construct from functor and left operand
        }

//_Left绑定了一个参数

//_Func一个二元函数对象

 

//这样就实现了像使用一元函数对象那样使用二元函数对象了

    result_type operator()(const argument_type& _Right) const
        {    // apply functor to operands
        return (op(value, _Right));
        }

 

bind1st测试代码如下

 

TestBind2nd就好理解了。它绑定了二元函数对象的第二个参数

抱歉!评论已关闭.