STL traits

STL traits的实现

traits 是一种能获取出你所需类型特性的方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
struct input_iterator_tag{};
struct output_iterator_tag{};
struct forward_iterator_tag :public input_iterator_tag{};
struct bidirectional_iterator_tag: public forward_iterator_tag{};
struct random_access_iterator_tag: public bidirectional_iterator_tag{};

template<class _Cat,class _T,class _Dis = int,
class _P = _T*, class _Ref = _T&>
struct iterator
{
typedef _Cat iterator_category;
typedef _T value_type;
typedef _Dis difference_type;
typedef _P pointer;
typedef _Ref reference;
};

template<class Iterator>
struct iterator_traits
{
typedef typename Iterator::iterator_category iterator_category;
typedef typename Iterator::value_type value_type;
typedef typename Iterator::difference_type difference_type;
typedef typename Iterator::pointer pointer;
typedef typename Iterator::reference reference;
};

template<class T>
struct iterator_traits<T*>
{
typedef random_access_iterator_tag iterator_category;
typedef T value_type;
typedef int 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 int difference_type;
typedef const T * pointer;
typedef const T & reference;
};
template<class Iterator>
typename iterator_traits<Iterator>::iterator_category
iterator_category(Iterator &) //迭代器的'类型'
{
typedef typename iterator_traits<Iterator>::iterator_category iterator_category;
return iterator_category();
}
template<class Iterator>
typename iterator_traits<Iterator>::value_type*
value_type(Iterator &) //迭代器所指之物类型
{
return static_cast<typename iterator_traits<Iterator>::value_type*>(0);
}

template<class Iterator>
typename iterator_traits<Iterator>::difference_type *
difference_type(Iterator &) //获取差值类型
{
return static_cast<typename iterator_traits<Iterator>::difference_type*>(0);
}

迭代器分类

stl_iterator

1
2
3
4
5
struct input_iterator_tag{};
struct output_iterator_tag{};
struct forward_iterator_tag :public input_iterator_tag{};
struct bidirectional_iterator_tag: public forward_iterator_tag{};
struct random_access_iterator_tag: public bidirectional_iterator_tag{};

advance例子

stl_traits