1. 前言
仿函数作为C++ STL 6大组件之一,它在行为类似函数,可作为算法的某种策略。这里补充C++ STL的6大组件的基本介绍:
1. 容器:其中包含各种数据结构,如vector、list、deque、set、map,用来存储数据。从实现的角度来看,STL容器是一种class template。
2. 算法:各种常用的算法如sort、search、copy、erase。从实现的角度来看,STL算法是function template
3. 迭代器:扮演容器预算法之间的胶合剂,是所谓的“泛型指针”,共有五种类型,以及他们的衍生变化。从实现的角度来看,迭代器是一种将operator*, operator->,operator++,operator-- 等指针相关操作予以重载的classtemplate。所有的STL容器都有附带有自己专属的迭代器,只有容器设计者才知道如何遍历自己的元素。原生指针(native pointer)也是一种迭代器。
4. 仿函数:行为类似函数,可作为算法的某种策略(policy)。从实现的角度来看,仿函数是一种重载了operator()的class 或是Class template,一般函数指针可视为狭义的仿函数
5. 配接器:一种用来修饰容器或仿函数或迭代器接口的东西。例如,STL提供的queue和stack,虽然看似容器,其实只能算是一种容器配接器,因为他们的底部完全借助deque,所有操作都是有底层deque提供,改变改变仿函数接口者,被称为function adapter;改变容器接口者,称为container adapter;改变迭代器接口者,称为iterator adapter。
6. 配置器:负责空间配置和管理。从实现的角度来看,配置器是一个实现了动态空间配置、空间管理、空间释放的Class template。
2. 用法
template<typename T> class AddItem
{
public:
T operator()(const T& item_a, const T& item_b)
{
return (item_a + item_b);
}
};
template<class T> class MinusItem
{
public:
T operator()(const T& item_a, const T& item_b)
{
return (item_a - item_b);
}
};
调用:
int b = AddItem<int>()(2, 8);
int c = MinusItem<int>()(2, 8);
补:在实际使用过程中使用上述的调用实际是使用了临时对象,它的出现使得程序干净清爽了很多。以为不需要定义相关的class或是struct的对象,再调用函数。否则就如下方式进行调用
AddItem<int>* additem = new AddItem<int>();
MinusItem<int>* minusitem = new MinusItem<int>();
int d = (*additem)(2, 8);
int e = (*minusitem)(2, 8);
//release
...