第5篇 迭代器

1 迭代器

迭代器:迭代器(iterators)是一种抽象设计概念。Design Patterns对iterator模式定义如下:提供一种方法,使之能够依序巡防某个聚合物(容器)所含的各个元素,而不需暴露该聚合物的内部表达方式。

1.1 迭代器(iterator)是一种smart pointer

迭代器最重要的操作就是对 operator* 和 operator-> 进行重载工作。

下面是一份简版的智能指针实现:

template<class T>
class Myauto_ptr
{
public:
    //explicit声明构造函数代表该类的对象不能够显示转换
    explicit Myauto_ptr(T *p = 0) :pointee(p){}
    template<class U>
    Myauto_ptr(Myauto_ptr<U>& rhs) :pointee(rhs.release()){}
    ~Myauto_ptr(){ delete pointee; }

    template<class U>
    Myauto_ptr<T>& operator=(Myauto_ptr<U>& rhs){
        if (this != &rhs)
            reset(rhs.release());
        return *this;
    }
    //const后置,代表常成员函数
    //关于C++对象、常变量、常成员函数可以参考
    //http://blog.csdn.net/e_road_by_u/article/details/52215193
    T& operator*() const{return *pointee; }
    T* operator->() const{return pointee; }
    T* get() const { return pointee; }

private:
    T *pointee;
};

1.2 迭代器的相应型别—Traits编程技法

关于typename的用法,可以学习<<Effective C++>>的条款42,或者参看此篇文章:http://harttle.com/2015/09/09/effective-cpp-42.html

Template Partial Specialization(偏特化):如果class template拥有一个以上的template参数,可以针对其中某个(或数个,并非全部)template参数进行偏特化工作。

//由此,面对下面一个class template
template<typename T>
class C {...};              //这个泛化版本允许(接受)T为任何型别
//它有一个形如下的partial specialization:
template<typename T>
class C<T*> {...};          //这个特化版本仅适用于“T为原生指针”的情况

下面的class template专门用来“萃取”迭代器的特性,而value type 正是迭代器的特性之一。

template <class T>
struct iterator_traits{     // traits意为“特性”
    typedef typename I::value_type value_type;
}
//其中的一个partial specialization如下:
template<class T>
struct iterator_traits<T*>{     //偏特化版------迭代器是个原生指针
    typedef T value_type;
}
另一个partial specialization如下:
template<class T>
struct iterator_traits<const T*>{       //偏特化版---当迭代器是个pointer-to-pointer
}

最常用的迭代器型别有五种:value type, difference type, pointer, reference, iterator catagoly。

template<class T>
struct iterator_traits {
    typedef typename I::iterator_category iterator_category;
    typedef typename I::value_type value_type;
    typedef typename I::difference_type defference_type;
    typedef typename I::pointer pointer;
    typedef typename I::reference reference;
} 

STL提供一个iterator class,如果每个新设计的迭代器都继承自它,就可保证符合STL所需之规范。

template<class Category,
         class T,
         class Distance = ptrdiff_t,
         class Pointer = T*,
         class Reference = T&>
struct iterator {
    typedef Category    iterator_category;
    typedef T           value_type;
    typedef Distance    difference_type;
    typedef Pointer     pointer;
    typedef Reference   reference;
}

traits编程技法大量运用于STL实现品中,它利用“内嵌型别”的编程技巧与编译器的template参数推导功能,增强C++未能提供的关于型别认证方面的能力,补充C++不为强型别语言的遗憾。了解traits编程语法,就向获得“芝麻开门”的口诀一样,从此得以一窥STL源码代码堂奥。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章