class template

std::unary_function

<functional>
template <class Arg, class Result> struct unary_function;
Unary function object base class
This is a base class for standard unary function objects.

Generically, function objects are instances of a class with member function operator() defined. This member function allows the object to be used with the same syntax as a regular function call, and therefore it can be used in templates instead of a pointer to a function.

In the case of unary function objects, this operator() member function takes one single parameter.

unary_function is just a base class, from which specific unary function objects are derived. It has no operator() member defined (derived classes are expected to define this) - it simply has two public data members that are typedefs of the template parameters. It is defined as:

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


Members

argument_type
Alias of the first template parameter, which is the type for the argument in member operator().
result_type
Alias of the second template parameter, which is the return type in member operator().

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// unary_function example
#include <iostream>
#include <functional>
using namespace std;

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

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

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

  result = IsOdd_object (input);

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

  return 0;
}


Possible output:

Please enter a number: 2
Number 2 is even.

See also