bind2nd:https://msdn.microsoft.com/zh-cn/library/3f0defz2

bind2nd可以将二元仿函数转化为一元仿函数,这看上去好像很神奇,其实它的实现很简单。

首先,二元仿函数会继承自binary_function,其实只是一些typedef,这些都将用于函数适配器。

template <class Arg1, class Arg2, class Result>
struct binary_function {
    typedef Arg1 first_argument_type;
    typedef Arg2 second_argument_type;
    typedef Result result_type;
};   

template <class T>
struct greater : public binary_function<T, T, bool> {
    bool operator()(const T& x, const T& y) const { return x > y; }
};

bind2nd将二元仿函数跟第二个参数型别作为模板型别,下面是具体实现:

template <class Operation, class T>
inline binder2nd<Operation> bind2nd(const Operation& op, const T& x) {
    typedef typename Operation::second_argument_type arg2_type;
    // 调用binder2nd
    return binder2nd<Operation>(op, arg2_type(x));
}

// binder2nd是一个一元仿函数(本身可以搭配函数适配器一起使用)
template <class Operation> 
class binder2nd
  : public unary_function<typename Operation::first_argument_type,
                          typename Operation::result_type> 
{
protected:
    // 传进来的二元仿函数
    Operation op;
    // 传进来的第二个参数  因为仿函数内部可以typedef  而函数指针则不行
    // 因此只能适配仿函数  而不能适配函数指针
    typename Operation::second_argument_type value;
public:
    // 构造函数
    binder2nd(const Operation& x,
            const typename Operation::second_argument_type& y) 
       : op(x), value(y) {}

    // 直接调用二元仿函数 
    typename Operation::result_type
    operator()(const typename Operation::first_argument_type& x) const {
        return op(x, value); 
    }
};




阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: c++