unary_function和binay_function

一、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;
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值