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