STL之迭代器与traits编程技法

iterator模式定义如下:

提供一种方法,使之能够依序巡防某个聚合物所含的各个元素,而又不暴露该聚合物的内部表达式。


迭代器是一种smart pointer:

举例auto_ptr

template<class T>

class auto_ptr {

public :

explicit auto_ptr(T *p = 0):pointee(p){}

~auto_ptr(){ delete pointee;}

template<class U>

auto_ptr(auto_ptr<U>& rhs):pointee( rhs.release() ){}

template<class U>

auto_ptr<T>& operator=(auto_ptr<U>& rhs){

if(this != rhs) reset( rhs,release );

return *rhs;

}

T& operator*() const { return *pointee; }

T* operator->() const { return pointee; }

T* get() const { return  pointee; }

private:

T* pointee;

}


迭代器的相应型别:利用function template的参数推导举例:

template<class I, class T>

void func_impl(I iter, T t)

{

T tmp;    //T就是迭代器所指之物的型别

}


template<class I>

inline void func(I iter)

{

func_impl(iter, *iter);

}


int main()

{

int i;

  fun(&i);

}

//参数可以推导,但是函数的返回值无法预知,引入内嵌类别,但是内嵌类别无法区分原生指针

//利用模板偏特化,声明萃取迭代器的特性的类模板

template<class I>

struct iterator_traits{

typedef typename I::value_type value;

}

多了一层间接性,拥有特化版本,识别原生指针

template<class T>

struct iterator_traits<T*>{

typedef T value_type;

}

包括指向常数对象的指针

template<class T>

struct iterator_traits<const T*>{

typedef T value;

}

difference_type:

template<class I>

struct iterator_traits

{

typedef typename I::difference_type difference_type;

}

template<class I>

struct iterator_traits<T*>

{

typedef  ptrdiff_t difference_type;

}

template<class I>

struct iterator_traits<const T*>

{

typedef  ptrdiff_t difference_type;

}


指针和引用

template<class I>

struct iterator_traits

{

typedef typename I::pointer  pointer;

typedef typename I::reference reference;

}


template<class T>

struct iterator_traits<T *>

{

typedef  T* pointer;

typedef  T& reference;

}

template<class T>

struct iterator_traits<T *>

{

typedef const T* pointer;

typedef const T& reference;

}


迭代器:

template <class I>

struct iterator_traits{

typedef typename I::iterator_category iterator_category;

}

template<class T>

struct iterator_traits<T *>

{

typedef random_access_iterator_tag         iterator_category;

}

template<class T>

struct iterator_traits<const T *>

{

typedef random_access_iterator_tag     iterator_category;

}


关于Traits技巧,推荐如下文章:
http://www.cnblogs.com/pugang/archive/2012/10/17/2727378.html

猜你喜欢

转载自blog.csdn.net/w1012747007/article/details/76098291