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源碼代碼堂奧。