1. unary_function
1.1 unary_function介绍
unary_funciton可以作为一个一元函数对象(又叫仿函数)的基类,它只定义了参数和返回值的类型,本身并不重载()操作符,这个任务交给派生类去完成。
1.2 unary_function源码
//TEMPLATE STRUCT unary_function
template<class _Arg, class _Result>
struct unary_function
{ //base class for unary functions
typedef _Arg argument_type;
typedef _Result result_type;
};
成员类型 | 定义 | 注释 |
---|---|---|
argument_type | 第一个模板参数(Arg) | ()重载函数的参数类型 |
result_type | 第二个模板参数(Result) | ()重载函数的返回值类型 |
1.3 unary_function例子
//unary_function example
#include <iostream> // std::cout, std::cin
#include <functional> // std::unary_function
//判断输入数据是否为Odd奇数?偶数是Even
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;
}
2. binary_function
2.1 binary_function介绍
binary_function可以作为一个二元函数对象的基类,它只定义了参数和返回值的类型,本身并不重载()操作符,这个任务交给派生类去完成。
2.2 binary_function源码
//TEMPLATE STRUCT binary_function
template<class _Arg1,
class _Arg2,
class _Result>
struct binary_function
{ //base class for binary functions
typedef _Arg1 first_argument_type;
typedef _Arg2 second_argument_type;
typedef _Result result_type;
};
成员类型 | 定义 | 注释 |
---|---|---|
first_argument_type | 第一个模板参数(First_Arg) | ()重载函数的第一个参数类型 |
second_argument_type | 第二个模板参数(Second_Arg) | ()重载函数的第二个参数类型 |
result_type | 第三个模板参数(Result) | ()重载函数的返回值类型 |
2.3 binary_function例子
//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;
}