traits意思爲特性, traits技巧就是根據迭代器的類型萃取出迭代器相關的類型。
爲了實現這個目標, 迭代器需要定義一些類型名稱value_type, difference_type, pointer, reference, iterator_category, 然後通過偏特化, 也可以對原生指針有很好的支持. 如果某個迭代器沒有遵行stl的類型定義約定,那麼這個迭代器就不能兼容於整個stl這個大家庭. 下面是一個類型定義:
template <class _Category, class _Tp, class _Distance = ptrdiff_t,
class _Pointer = _Tp*, class _Reference = _Tp&>
struct iterator {
typedef _Category iterator_category;
typedef _Tp value_type;
typedef _Distance difference_type;
typedef _Pointer pointer;
typedef _Reference reference;
};
爲了避免寫得迭代器忘記滿足要求,可以將自己的迭代器從這個iterator中繼承.例如:
template<class _Tp>
struct ListIter : public std::iterator<std::forward_iterator_tag, _Tp>
{ ... }