std::binder1st, std::binder2nd

来自cppreference.com
< cpp‎ | utility‎ | functional
 
 
 
函数对象
函数调用
(C++17)(C++23)
恒等函数对象
(C++20)
旧式绑定器与适配器
(C++17 前*)
(C++17 前*)
(C++17 前*)
(C++17 前*)
(C++17 前*)(C++17 前*)(C++17 前*)(C++17 前*)
(C++20 前*)
(C++20 前*)
binder1stbinder2nd
(C++17 前*)(C++17 前*)
(C++17 前*)(C++17 前*)

(C++17 前*)
(C++17 前*)(C++17 前*)(C++17 前*)(C++17 前*)
(C++20 前*)
(C++20 前*)
 
在标头 <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 <cmath>
#include <functional>
#include <iostream>
#include <vector>
 
const double pi = std::acos(-1); // C++20 中使用 std::numbers::pi
 
int main()
{
    // C++11 中弃用,C++17 中移除
    auto f1 = std::bind1st(std::multiplies<double>(), pi / 180.0);
 
    // C++11 的替代方案
    auto f2 = [](double a) { return a * pi / 180.0; };
 
    for (double n : {0, 30, 45, 60, 90, 180})
        std::cout << n << \t" << std::fixed << "= "
                  << f1(n) << " 弧度(使用绑定器)\t="
                  << f2(n) << " 弧度(使用 lambda)\n"
                  << std::defaultfloat;
}

输出:

0°	= 0.000000 弧度(使用绑定器)	=0.000000 弧度(使用 lambda)
30°	= 0.523599 弧度(使用绑定器)	=0.523599 弧度(使用 lambda)
45°	= 0.785398 弧度(使用绑定器)	=0.785398 弧度(使用 lambda)
60°	= 1.047198 弧度(使用绑定器)	=1.047198 弧度(使用 lambda)
90°	= 1.570796 弧度(使用绑定器)	=1.570796 弧度(使用 lambda)
180°	= 3.141593 弧度(使用绑定器)	=3.141593 弧度(使用 lambda)

缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告应用于出版时的行为正确行为
LWG 109C++98operator() 无法修改传递给它的实参添加重载以处理这种情况

参阅

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