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