STL学习之路之仿函数

STL中的仿函数(或者叫做函数对象):可以实现类似于函数一样的类型,函数最直接的调用形式就是:返回值 函数名(参数列表),仿函数实现了operator()操作符,使用类似于函数。

同时,STL还为仿函数提供了强大的配接器,也就是适配器Adapters,这些适配器本身也属于仿函数,调用方式同样类似于函数。更进一步,这些适配器可以和仿函数、函数、适配器再进行绑定、组合、适配,完成更加复杂的功能。

这部分应该是STL中最简单的部分,实现也比较简单。另外C++11标准对这部分调整比较大,我们先不考虑。暂且把它作为一个学习template的例子。

#ifndef TESTFUNCTIONAL_H
#define TESTFUNCTIONAL_H

namespace Test{
template<class _Arg, class _Result>
struct unary_function
{
	typedef _Arg argument_type;
	typedef _Result result_type;
};

template<class _Arg1, class _Arg2, class _Result>
struct binary_function
{
	typedef _Arg1 first_argument_type;
	typedef _Arg2 second_argument_type;
	typedef _Result result_type;
};

template<class _Tp>
struct plus : public binary_function<_Tp, _Tp, _Tp>{
	_Tp operator()(const _Tp& _x, const _Tp& _y) const {	return _x + _y; }
};

template<class _Tp>
struct minus : public binary_function<_Tp, _Tp, _Tp>{
	_Tp operator()(const _Tp& _x, const _Tp& _y) const { return _x - _y; }
};

template<class _Tp>
struct multiplies : public binary_function<_Tp, _Tp, _Tp>{
	_Tp operator()(const _Tp& _x, const _Tp& _y) const { return _x * _y; }
};

template<class _Tp>
struct divides : public binary_function<_Tp, _Tp, _Tp>{
	_Tp operator()(const _Tp& _x, const _Tp& _y) const { return _x / _y; }
};

template<class _Tp>
struct modulus : public binary_function<_Tp, _Tp, _Tp>{
	_Tp operator()(const _Tp& _x, const _Tp& _y) const { return _x % _y; }
};

template<class _Tp>
struct negate : public unary_function<_Tp, _Tp>{
	_Tp operator()(const _Tp& _x) const { return -_x; }
};

template <class _Tp>
struct equal_to : public binary_function<_Tp,_Tp,bool> 
{
	bool operator()(const _Tp& __x, const _Tp& __y) const { return __x == __y; }
};

template <class _Tp>
struct not_equal_to : public binary_function<_Tp,_Tp,bool> 
{
	bool operator()(const _Tp& __x, const _Tp& __y) const { return __x != __y; }
};

template <class _Tp>
struct greater : public binary_function<_Tp,_Tp,bool> 
{
	bool operator()(const _Tp& __x, const _Tp& __y) const { return __x > __y; }
};

template <class _Tp>
struct less : public binary_function<_Tp,_Tp,bool> 
{
	bool operator()(const _Tp& __x, const _Tp& __y) const { return __x < __y; }
};

template <class _Tp>
struct greater_equal : public binary_function<_Tp,_Tp,bool>
{
	bool operator()(const _Tp&a
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值