std::binder1st, std::binder2nd
定义于头文件 <functional> |
||
template< class Fn > class binder1st |
(1) | (在 C++11 中弃用) (在 C++17 中移除) |
template< class Fn > class binder2nd |
(2) | (在 C++11 中弃用) (在 C++17 中移除) |
一个将实参绑定到二元函数的函数对象。
形参的值在构造时传递给对象并存储在对象内部。每当通过 operator()
调用函数对象时,存储的值将作为其中一个实参传递,另一个实参作为 operator()
的实参传递。结果函数对象是一元函数。
[编辑] 示例
#include <cmath> #include <functional> #include <iostream> #include <vector> const double pi = std::acos(-1); // use std::numbers::pi in C++20 int main() { // deprecated in C++11, removed in C++17 auto f1 = std::bind1st(std::multiplies<double>(), pi / 180.0); // C++11 replacement 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 (using binder)\t= " << f2(n) << " rad (using lambda)\n" << std::defaultfloat; }
输出
0° = 0.000000 rad (using binder) = 0.000000 rad (using lambda) 30° = 0.523599 rad (using binder) = 0.523599 rad (using lambda) 45° = 0.785398 rad (using binder) = 0.785398 rad (using lambda) 60° = 1.047198 rad (using binder) = 1.047198 rad (using lambda) 90° = 1.570796 rad (using binder) = 1.570796 rad (using lambda) 180° = 3.141593 rad (using binder) = 3.141593 rad (using lambda)
[编辑] 缺陷报告
以下行为变更缺陷报告被追溯应用到先前发布的 C++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 109 | C++98 | operator() 无法修改传递给它的实参 |
添加重载以处理此问题 |
[编辑] 参见
(在 C++11 中弃用)(在 C++17 中移除) |
将一个实参绑定到二元函数 (函数模板) |