STL源码剖析 笔记之七 仿函数

第七章 仿函数
仿函数又称函数对象,一种具有函数特质的对象。
用仿函数替代函数指针的原因,函数指针不能满足STL对抽象性的要求,也不能满足软件积木的要求(与其他STL组件配搭)。
所有的仿函数定义于<stl_function.h>,使用时需包含<funcional>头文件。

STL仿函数的可配接性
STL仿函数应该有能力被函数配接器修饰,彼此像积木一样串联。为了拥有配接能力,仿函数必须定义自己的相应类型。
就像迭代器如果要融入整个STL,也必须依照规定定义自己的5个相应类型一样。
这些相应类型是为了让配接器能够取出,获得仿函数的某些信息。
主要用来表现函数参数类型和返回值类型。
为了方便,<stl_function.h>定义了2个class,分别代表一元和二元仿函数。任何仿函数均可继承自他们,自动拥有这些类型。
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;
}; 

算术类仿函数
加(plus)、减(minus)、乘(multiplies)、除(divides)、取模(modulus)、取反(negation)
证同元素 identity element
所谓运算op的证同元素,意思是数值A若与该元素做op元算,会得到A自己。如,加法的证同元素为0,乘法的证同元素为1。

关系远算类仿函数
等于、不等于、大于、大于等于、小于、小于等于
逻辑运算类仿函数
And、Or、Not
这些功能极其简单的仿函数存在的主要用途是为了搭配STL算法。

证同(identity)、选择(select)、投射(project)
之所以不在STL中直接使用这些操作,而要再划分出一层,是为了间接性(间接性是抽象化的重要工具)。
证同函数
运用于<stl_set.h>中,因为set的键值即实值
template <class T>  //返回本身
struct identity : public unary_function<T, T> {
  const T& operator()(const T& x) const { return x; }
};
选择函数 
运用于<stl_map.h>,因为map中pair的第一个元素为键值
template <class Pair> //接受一个pair,返回第一个元素
struct select1st : public unary_function<Pair, typename Pair::first_type> {
  const typename Pair::first_type& operator()(const Pair& x) const
  {
    return x.first;
  }
};

template <class Pair> //接受一个pair,返回第二个元素
struct select2nd : public unary_function<Pair, typename Pair::second_type> {
  const typename Pair::second_type& operator()(const Pair& x) const
  {
    return x.second;
  }
};
投射函数
template <class Arg1, class Arg2> //传回第一参数,忽略第二参数
struct project1st : public binary_function<Arg1, Arg2, Arg1> {
  Arg1 operator()(const Arg1& x, const Arg2&) const { return x; }
};

template <class Arg1, class Arg2> //传回第二参数,忽略第一参数
struct project2nd : public binary_function<Arg1, Arg2, Arg2> {
  Arg2 operator()(const Arg1&, const Arg2& y) const { return y; }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值