類模板
<functional>
std::binder2nd
template <class Operation> class binder2nd;
生成綁定了第二個引數的函式物件類
透過繫結第二個引數為固定值,從二元物件類*Operation*生成一元函式物件類。
binder2nd通常用作一個型別。可以使用函式
bind2nd(也在標頭檔案
<functional>中定義)直接構造該型別的物件。
binder2nd使用*二元函式物件*作為引數進行構造。該物件的副本在其成員
operator()中用於透過其引數和構造時設定的固定值生成結果。
該類派生自
unary_function,通常定義為
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
template <class Operation> class binder2nd
: public unary_function <typename Operation::first_argument_type,
typename Operation::result_type>
{
protected:
Operation op;
typename Operation::second_argument_type value;
public:
binder2nd ( const Operation& x,
const typename Operation::second_argument_type& y) : op (x), value(y) {}
typename Operation::result_type
operator() (const typename Operation::first_argument_type& x) const
{ return op(x,value); }
};
|
binder2nd類特別設計用於繫結派生自
binary_function的函式物件(*操作*)(它需要成員
first_argument_type和
second_argument_type).
成員
- 建構函式
- 透過將二元函式物件的第二個引數繫結到一個值,來構造一個派生自該二元函式物件的類。
- operator()
- 成員函式接收單個引數,並呼叫用於構造的二元函式物件,將其第二個引數繫結到特定值,然後返回結果。
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
// binder2nd example
#include <iostream>
#include <functional>
#include <algorithm>
using namespace std;
int main () {
binder2nd < less<int> > IsNegative (less<int>(),0);
int numbers[] = {10,-20,-30,40,-50};
int cx;
cx = count_if (numbers,numbers+5,IsNegative);
cout << "There are " << cx << " negative elements.\n";
return 0;
}
|
輸出
There are 3 negative elements.
|
另見
- bind2nd
- 返回第二個引數被繫結的函式物件 (函式模板)
- binder1st
- 生成第一個引數被繫結的函式物件類 (類模板)
- unary_function
- 一元函式物件基類 (類模板)
- binary_function
- 二元函式物件基類 (類模板)