Namespaces
Variants

std::binder1st, std::binder2nd

来自 zh.cppreference.net
 
 
 
函数对象
函数调用
(C++17)(C++23)
恒等函数对象
(C++20)
透明运算符包装器
(C++14)
(C++14)
(C++14)
(C++14)  
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)

旧的绑定器和适配器
(直到 C++17*)
(直到 C++17*)
(直到 C++17*)
(直到 C++17*)  
(直到 C++17*)
(直到 C++17*)(直到 C++17*)(直到 C++17*)(直到 C++17*)
(直到 C++20*)
(直到 C++20*)
(直到 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 std::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) << " rad (使用绑定器)\t= "
                  << f2(n) << " rad (使用 lambda)\n"
                  << std::defaultfloat;
}

输出:

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

缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的C++标准。

缺陷报告 适用标准 发布时行为 正确行为
LWG 109 C++98 operator() could not modify to argument passed to it added overloads to handle this

参见

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