您的位置:首页 > 其它

unary_function和binay_function

2017-09-09 18:52 393 查看

一、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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: