Namespaces
Variants

std:: binder1st, std:: binder2nd

From cppreference.net
Utilities library
Function objects
Function invocation
(C++17) (C++23)
Identity function object
(C++20)
Old binders and adaptors
( until C++17* )
( until C++17* )
( until C++17* )
( until C++17* )
( until C++17* ) ( until C++17* ) ( until C++17* ) ( until C++17* )
( until C++20* )
( until C++20* )
binder1st binder2nd
( until C++17* ) ( until C++17* )
( until C++17* ) ( until C++17* )

( until C++17* )
( until C++17* ) ( until C++17* ) ( until C++17* ) ( until C++17* )
( until C++20* )
( until 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 中移除)
将单个参数绑定到二元函数
(函数模板)