類模板
<functional>

std::binary_function

template <class Arg1, class Arg2, class Result> struct binary_function;
template <class Arg1, class Arg2, class Result> struct binary_function; // deprecated
二元函式物件基類
注意:該類在 C++11 中已被棄用。

這是一個標準*二元函式物件*的基類。

一般而言,*函式物件*是指定義了成員函式 operator() 的類的例項。這個成員函式允許該物件以與普通函式呼叫相同的語法使用,因此當需要通用函式型別時,它的型別可以用作模板引數。

對於*二元函式物件*,這個 operator() 成員函式接受兩個引數。

binary_function 只是一個基類,具體的二元函式物件從中派生。它沒有定義 operator() 成員(派生類需要定義它)——它只有三個公共資料成員,它們是模板引數的*typedef*。它定義為

1
2
3
4
5
6
template <class Arg1, class Arg2, class Result>
  struct binary_function {
    typedef Arg1 first_argument_type;
    typedef Arg2 second_argument_type;
    typedef Result result_type;
  };

成員

成員型別定義說明
first_argument_type第一個模板引數(Arg1成員 operator() 的第一個引數的型別
second_argument_type第二個模板引數(Arg2成員 operator() 的第二個引數的型別
return_type第三個模板引數(Result成員 operator() 返回的型別

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// binary_function example
#include <iostream>     // std::cout, std::cin
#include <functional>   // std::binary_function

struct Compare : public std::binary_function<int,int,bool> {
  bool operator() (int a, int b) {return (a==b);}
};

int main () {
  Compare Compare_object;
  Compare::first_argument_type input1;
  Compare::second_argument_type input2;
  Compare::result_type result;

  std::cout << "Please enter first number: ";
  std::cin >> input1;
  std::cout << "Please enter second number: ";
  std::cin >> input2;

  result = Compare_object (input1,input2);

  std::cout << "Numbers " << input1 << " and " << input2;
  if (result)
	  std::cout << " are equal.\n";
  else
	  std::cout << " are not equal.\n";

  return 0;
}

可能的輸出

Please enter first number: 2
Please enter second number: 33
Numbers 2 and 33 are not equal.


另見