std::binder1st, std::binder2nd
ja.cppreference.net より
| ヘッダ <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 (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で削除)
|
二項関数に1つの引数をバインドする
(関数テンプレート) |