std::binder1st, std::binder2nd

< cpp‎ | utility‎ | functional
定义于头文件 <functional>
template< class Fn >

class binder1st : public std::unary_function<typename Fn::second_argument_type,
                                             typename Fn::result_type> {
protected:
   
    Fn op;
    typename Fn::first_argument_type value;

public:

    binder1st(const Fn& fn,
              const typename Fn::first_argument_type& value);

    typename Fn::result_type
        operator()(const typename Fn::second_argument_type& x) const;

    typename Fn::result_type
        operator()(typename Fn::second_argument_type& x) const;

};
(1) (C++11 中弃用)
(C++17 中移除)
template< class Fn >

class binder2nd : public unary_function<typename Fn::first_argument_type,
                                        typename Fn::result_type> {
protected:
    Fn op;
    typename Fn::second_argument_type value;
public:
    binder2nd(const Fn& fn,
              const typename Fn::second_argument_type& value);

    typename Fn::result_type
        operator()(const typename Fn::first_argument_type& x) const;

    typename Fn::result_type
        operator()(typename Fn::first_argument_type& x) const;

};
(2) (C++11 中弃用)
(C++17 中移除)

绑定实参到二元函数的函数对象。

在构造时将形参的值传递给对象并在对象中存储。凡在通过 operator() 调用函数对象时,均将存储的值作为实参之一传递,将另一实参作为 operator() 的实参传递。产生的函数对象是一元函数。

1) 绑定第一参数为在对象构造时给定的值 value
2) 绑定第二参数为在对象构造时给定的值 value

示例

#include <iostream>
#include <functional>
#include <cmath>
#include <vector>
const double pi = std::acos(-1);
int main()
{
    // C++11 中弃用, C++17 中移除
    std::binder1st<std::multiplies<double>> f1 = std::bind1st(
                                                   std::multiplies<double>(), pi / 180.);
 
    // C++11 替代
    auto f2 = [](double a){ return a*pi/180.; };
 
    for(double n : {0, 30, 45, 60, 90, 180})
        std::cout << n << " deg = " << f1(n) << " rad (using binder) "
                                    << f2(n) << " rad (using lambda)\n";
}

输出:

0 deg = 0 rad (using binder) 0 rad (using lambda)
30 deg = 0.523599 rad (using binder) 0.523599 rad (using lambda)
45 deg = 0.785398 rad (using binder) 0.785398 rad (using lambda)
60 deg = 1.0472 rad (using binder) 1.0472 rad (using lambda)
90 deg = 1.5708 rad (using binder) 1.5708 rad (using lambda)
180 deg = 3.14159 rad (using binder) 3.14159 rad (using lambda)

参阅

(C++11 中弃用)(C++17 中移除)
将一个实参绑定到二元函数
(函数模板)