標籤:
traits編程技法利用了“內嵌型別”的編程技巧與編譯器的template參數推導功能。
下面主要看看利用traits編程技法實現的迭代器萃取機制。
5種迭代器類型定義:
struct input_iterator_tag {};struct output_iterator_tag {};struct forward_iterator_tag : public input_iterator_tag {};struct bidirectional_iterarot_tag : public forward_iterator_tag {};struct random_access_iterator_tag : public bidirectional_iterarot_tag {};
std::iterator的定義
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;};
如果想和STL協同工作,自行定義的迭代器必須定義iterator_category、value_type、difference_type、pointer、reference這五大內嵌型別。為了方便,STL定義了std::iterator這個基類,自訂的迭代器只要繼承這個基類
就可以了。但要注意的是,並不是STL中的所有迭代器都繼承了這個基類,比如_deque_iterator。
"榨汁機"traits
template <class Iterator>struct iterator_traits { typedef typename Iterator::iterator_category iterator_category; typedef typename Itetator::value_type value_type; typedef typename Iterator::difference_type difference_type; typedef typename Iterator::pointer pointer; typedef typename Iterator::reference reference;};
由於原生指標也是一種迭代器,但是原生指標沒有內嵌型別,因此,iterator_traits需要為原生指標提供特化版本。
template <class T>struct iterator_traits<T*> { typedef random_access_iterator_tag iterator_category; typedef T value_type; typedef ptrdiff_t difference_type; typedef T* pointer; typedef T& reference;};template <class T>struct iterator_traits<const T*> { typedef random_access_iterator_tag iterator_category; typedef T value_type; typedef ptrdiff_t difference_type; typedef const T* pointer; typedef const T& reference;};
STL之traits編程技法