您的位置:首页 > 大数据 > 人工智能

【STL】迭代器以及“特性萃取机”iterator_traits

2014-05-14 16:02 363 查看
迭代器是一种行为类似指针的对象,而指针的各种行为中最常见的便是解引用(*)和成员访问(->),此外还有operator++。因此,迭代器最重要的编程工作是对operator*和operator->进行重载工作。关于这部分的代码,可以参考class auto_ptr。

迭代器一般会和某种容器相关联,指向某种类型的元素,这种元素的类型(value_type)叫做相应类型。常用的相应类型有五种:
value_type:迭代器所指对象的类型。

difference_type:两个迭代器之间的距离。
reference:容器内元素的引用。

pointer:容器内元素的指针。

iterator_category:表示迭代器类型,根据迭代器类型激活重载函数。关于这一点,可以参考STL算法advance()。

如果某个函数的返回类型为迭代器的相应类型,那么靠“模板实参推断”是无法实现的,而“特性萃取”技术能够很好的解决这个问题。
为了获得迭代器的相应类型,STL采用了一种称为特性萃取的技术,能够获得迭代器(包括原生指针)的相应类型:
template <class Iterator>
struct iterator_traits {
typedef typename Iterator::iterator_category iterator_category;
typedef typename Iterator::value_type        value_type;
typedef typename Iterator::difference_type   difference_type;
typedef typename Iterator::pointer           pointer;
typedef typename Iterator::reference         reference;
};


针对原生指针的特化版本:
template <class T>
struct iterator_traits<T*> {  // 特化版本,接受一个T类型指针
typedef random_access_iterator_tag iterator_category;
typedef T                          value_type;
typedef ptrdiff_t                  difference_type;
typedef T*                         pointer;
typedef T&                         reference;
};

template <class T>
struct iterator_traits<const T*> {  // 特化版本,接受一个T类型const指针
typedef random_access_iterator_tag iterator_category;
typedef T                          value_type;
typedef ptrdiff_t                  difference_type;
typedef const T*                   pointer;
typedef const T&                   reference;
};


当然,为了符合STL规范,用户自定义的迭代器必须添加这些相应类型,特性萃取机才能有效运作。

参考:
《STL源码剖析》 P80、P85.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: