Chinaunix首页 | 论坛 | 博客
  • 博客访问: 255195
  • 博文数量: 21
  • 博客积分: 1263
  • 博客等级: 准尉
  • 技术积分: 697
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-24 00:05
个人简介

专注于Answers Ranking, Answer Monitor和log处理。

文章分类
文章存档

2014年(5)

2012年(16)

分类: C/C++

2012-04-23 09:27:43

上次讲到在迭代器中对于指针的处理是使用的是模板的偏特化(partial specializition),所谓模板的偏特化就是对我们对模板提供另一份定义,对其中某些参数作出进一步的限制。如我们定义了一个模板类处理某种相似的操作,但是对于其中某个类,我们不进行任何操作,这样就可以对那个类再重新定义一个模板来处理。对于原生指针类型,如int *,我们要萃取的类型就是:int。

  1. template <class T>
  2. struct MyIter {
  3.     typedef T value_type;
  4.     //...
  5. };

  6. template <class T>
  7. struct MyIter<T *> {
  8.     typedef T value_type;
  9.     //...
  10. };

  11. template <class T>
  12. struct MyIter<const T *> {
  13.     typedef T value_type;
  14.     //...
  15. };
迭代器的traits定义了五种型别以供使用,并设计了pointer和const pointer的特化版本:

  1. template <class _Iterator>
  2. struct iterator_traits {
  3.   typedef typename _Iterator::iterator_category iterator_category;
  4.   typedef typename _Iterator::value_type value_type;
  5.   typedef typename _Iterator::difference_type difference_type;
  6.   typedef typename _Iterator::pointer pointer;
  7.   typedef typename _Iterator::reference reference;
  8. };

  9. template <class _Tp>
  10. struct iterator_traits<_Tp*> {
  11.   typedef random_access_iterator_tag iterator_category;
  12.   typedef _Tp value_type;
  13.   typedef ptrdiff_t difference_type;
  14.   typedef _Tp* pointer;
  15.   typedef _Tp& reference;
  16. };

  17. template <class _Tp>
  18. struct iterator_traits<const _Tp*> {
  19.   typedef random_access_iterator_tag iterator_category;
  20.   typedef _Tp value_type;
  21.   typedef ptrdiff_t difference_type;
  22.   typedef const _Tp* pointer;
  23.   typedef const _Tp& reference;
  24. };
除了第一个其实看定义就能看出来大概意思, value_type是指类型, difference_type是指两个迭代器之间的元素个数等等。而iterator_category代表什么呢?代表迭代器的型别,进一步讲就是它代表了这个迭代器可以怎样移动。
  1. struct input_iterator_tag {};
  2. struct output_iterator_tag {};
  3. struct forward_iterator_tag : public input_iterator_tag {};
  4. struct bidirectional_iterator_tag : public forward_iterator_tag {};
  5. struct random_access_iterator_tag : public bidirectional_iterator_tag {};
这就是迭代器的型别了,共五种。那它有什么用呢?对,为了效率!前面讲过在构造与析造的时候也是为了效率我们使用type_traits来提升效率,现在我们需要做的就是同样的工作:即重载不同的模板,让其自己挑选最适合自己的来执行。那这样我们自己的类也可以使用STL里面的迭代器,只要我们也定义了上面五种类型。STL里面也有一个我们可以通过继承它来实现:

  1. template <class _Category, class _Tp, class _Distance = ptrdiff_t,
  2.           class _Pointer = _Tp*, class _Reference = _Tp&>
  3. struct iterator {
  4.   typedef _Category iterator_category;
  5.   typedef _Tp value_type;
  6.   typedef _Distance difference_type;
  7.   typedef _Pointer pointer;
  8.   typedef _Reference reference;
  9. };





阅读(2227) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~