類模板
<functional>

std::unary_function

template <class Arg, class Result> struct unary_function;
template <class Arg, class Result> struct unary_function; // deprecated
一元函式物件基類
注意:此類已在 C++11 中棄用。

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

一般而言,函式物件是定義了成員函式operator()的類的例項。此成員函式允許物件使用與常規函式呼叫相同的語法進行使用,因此當期望通用函式型別時,其型別可以用作模板引數。

對於一元函式物件,此operator()成員函式接受一個引數。

unary_function只是一個基類,特定的(一元)函式物件從此基類派生。它沒有定義operator()成員(派生類應定義它)——它只有兩個公共資料成員,它們是模板引數的typedef。它的定義如下:

1
2
3
4
5
template <class Arg, class Result>
  struct unary_function {
    typedef Arg argument_type;
    typedef Result result_type;
  };

成員型別

成員型別定義說明
argument_type第一個模板引數(Arg成員 operator() 中引數的型別
result_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
// unary_function example
#include <iostream>     // std::cout, std::cin
#include <functional>   // std::unary_function

struct IsOdd : public std::unary_function<int,bool> {
  bool operator() (int number) {return (number%2!=0);}
};

int main () {
  IsOdd IsOdd_object;
  IsOdd::argument_type input;
  IsOdd::result_type result;

  std::cout << "Please enter a number: ";
  std::cin >> input;

  result = IsOdd_object (input);

  std::cout << "Number " << input << " is " << (result?"odd":"even") << ".\n";

  return 0;
}

可能的輸出

Please enter a number: 2
Number 2 is even.


另見