template <typename _Category, typename _Tp, typename _Distance=ptrdiff_t,
                 typename _Pointer=_Tp*, typename _Reference=_Tp&>
struct iterator
{
    typedef _Category iterator_category; // 有很多不同种类的iterator,
                                                              // 比如下面的reverse_iterator,random_access_iterator等等
    typedef _Tp value_type;
    typedef _Distance difference_type;    // 计算两个iterator之间的相对值
    typedef _Pointer pointer;
    typedef _Reference reference;
}

// Traits只是将typedef转向到_Iterator上;然后定义了2个偏特化,为了在模板实例化时找到更好的匹配。
template <typename _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 <typename _Tp>
struct iterator_traits<_Tp*>
{
    typedef random_access_iterator_tag iterator_category; // 注意这个地方,iterator的类型不是primary template
                                                                                           // 中的iterator::iterator_category。
    typedef _Tp value_type;
    typedef ptrdiff_t difference_type;
    typedef _Tp* pointer;
    typedef _Tp& reference;
};

template <typename _Tp>
struct iterator_traits<const _Tp*>
{
    typedef random_access_iterator_tag iterator_category;
    typedef _Tp value_type;
    typedef ptrdiff_t difference_type;
    typedef const _Tp* pointer;
    typedef const _Tp& reference;
};

template <typename _Iterator>
class reverse_iterator
    : public iterator<typename iterator_traits<_Iterator>::iterator_category,
                              typename iterator_traits<_Iterator>::value_type,
                              typename iterator_traits<_Iterator>::difference_type,
                              typename iterator_traits<_Iterator>::pointer,
                              typename iterator_traits<_Iterator>::reference>
{
protected:
    _Iterator current;
public:
    // 实际上,接下来的typedef,我认为是没有有必要的,因为它跟其继承自iterator里的typedef是一样的。
    // 但是STL作为一个具有工业强度的类库,难道会包含无用的代码?
    // 无解
    typedef _Iterator iterator_type;
    typedef typename iterator_traits<_Iterator>::difference_type difference_type;
    typedef typename iterator_traits<_Iterator>::reference reference;
    typedef typename iterator_triats<_Iterator>::pointer pointer;
public:
    … // other implementations.
};

Advertisements