标签:type 原创 blog ref class const lin www. typedef
摘要: 摘要: 摘要: 技术在于交流、沟通,本文为博主原创文章转载请注明出处并保持作品的完整性
仿函数的实现:声明一个类,重载它的operator call ("()"操作符)
template<typename T> class lineFeed { public: void operator()(const T &x) { cout<<x<<endl; } };
仿函数只为算法服务,但是像上面这种声明方式,虽然在有些时候可以使用,但是却不能融入STL,因为有可能在"仿函数适配器"上出现编译错误,下面我们来看看STL中的仿函数.
仿函数的使用可以看一下我的上一节博客,虽然都没有继承自 binary_function<T,T,bool>,unary_function<T,bool>
STL中的仿函数大致可以分为三个类
1.算数类
template<typename _Tp>
struct plus : public binary_function<_Tp, _Tp, _Tp>
{
_Tp
operator()(const _Tp& __x, const _Tp& __y) const
{ return __x + __y; }
};
template<typename _Tp>
struct minus : public binary_function<_Tp, _Tp, _Tp>
{
_Tp
operator()(const _Tp& __x, const _Tp& __y) const
{ return __x - __y; }
};
...
2.逻辑运算类
template<typename _Tp>
struct logical_and : public binary_function<_Tp, _Tp, bool>
{
bool
operator()(const _Tp& __x, const _Tp& __y) const
{ return __x && __y; }
};
template<typename _Tp>
struct logical_or : public binary_function<_Tp, _Tp, bool>
{
bool
operator()(const _Tp& __x, const _Tp& __y) const
{ return __x || __y; }
};
template<typename _Tp>
struct logical_not : public unary_function<_Tp, bool>
{
bool
operator()(const _Tp& __x) const
{ return !__x; }
};
...
3.相对关系类
template<typename _Tp>
struct equal_to : public binary_function<_Tp, _Tp, bool>
{
bool
operator()(const _Tp& __x, const _Tp& __y) const
{ return __x == __y; }
};
template<typename _Tp>
struct not_equal_to : public binary_function<_Tp, _Tp, bool>
{
bool
operator()(const _Tp& __x, const _Tp& __y) const
{ return __x != __y; }
};
...
我们会看到所有的STL仿函数都需要继承binary_function<T, T, bool>(两个参数)或者unary_function<T, bool>(一个参数),只有继承自这两种父类,你声明的仿函数才可以融入STL
上面提及到仿函数适配器, 如果不继承上面这两种类, 在执行到某个阶段会报错.报错的原因我会在下节适配中中分析
下面是binary_function<>与unary_function<>的源码
binary_function<T, T, bool>,发现binary_function<>
template<typename _Arg1, typename _Arg2, typename _Result>
struct binary_function
{
/// @c first_argument_type is the type of the first argument
typedef _Arg1 first_argument_type;
/// @c second_argument_type is the type of the second argument
typedef _Arg2 second_argument_type;
/// @c result_type is the return type
typedef _Result result_type;
};
unary_function<T, bool>
template<typename _Arg, typename _Result>
struct unary_function
{
/// @c argument_type is the type of the argument
typedef _Arg argument_type;
/// @c result_type is the return type
typedef _Result result_type;
};
写仿函数,一定要继承上面这两个类.
参考侯捷<<STL源码剖析>>
标签:type 原创 blog ref class const lin www. typedef
原文地址:http://www.cnblogs.com/LearningTheLoad/p/7594646.html