一、unary_function详解
unary_function可以作为一个一元函数对象的基类,它只定义了参数和返回值的类型,本身并不重载()操作符,这个任务应该交由派生类去完成。其定义如下:
template <class Arg, Class Result>
struct unary_function
{
typedef Arg argument_type;
typedef Result result_type;
}
成员类型 | 定义 | 注释 |
---|---|---|
argument_type | 第一个模板参数 (Arg) | ()重载函数的参数类型 |
result_type | 第二个模板参数(Result) | ()重载函数的返回值类型 |
例子如下:
#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;
}
二、binary_function详解
binary_funciton 用来呈现二元函数的第一个参数型别、第二个参数类型,以及返回值类型 ,其定义如下:
template <classArg1, classArg2, class Result>
{
typedef Arg1 first_argument_type;
typedef Arg2 second_argument_type;
typedef Result result_type;
}
成员类型 | 定义 | 注释 |
---|---|---|
first_argument_type | 第一个模板参数(Arg1) | 第一个模板参数(Arg1) |
second_argument_type | 第一个模板参数(Arg1) | ()重载函数的第二个参数类型 |
return_type | 第一个模板参数(Arg1) | ()重载函数的返回值类型 |
使用例子如下:
template <class T>
struct plus : public binary_function <T, T, T>
{
T operator () (const T &x, const T &y) const {return x + y;}
}
Plus pluss;
Plus::first_argument_type x;
Plus::second_argument_type y;
Plus::result_type reasult;
x = 1;
y = 2;
reasult = pluss (x, y);
std::cout << reasult << std::endl;