iterator_traits
SGI STL中的实现如下所示:
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 I> struct iterator_traits { typedef typename I::value_type value_type; typedef typename I::differenct_type differenct_type; typedef typename I::pointer pointer; typedef typename I::reference referenct; typedef typename I::iterator_category iterator_category; }; template <class T> struct iterator_traits<T *> {
};typedef T value_type; typedef ptrdiff_t differenct_type; typedef T* pointer; typedef T& referenct; typedef random_access_iterator_tag iterator_category;
template <class T> struct iterator_traits<const T *> {
};typedef T value_type; typedef ptrdiff_t differenct_type; typedef const T* pointer; typedef const T& referenct; typedef random_access_iterator_tag iterator_category;
__type_traits
__type_traits不是STL的内容,是SGI STL中自己提供的。iterator_traits用来获得iterator的类型信息,__type_traits用来获得任何一个type的一些信息。但其实现思路与iterator_traits略有不同。
先看其实现:
template <class T> struct __type_traits { typedef __true_type this_dummy_member_must_be_first; typedef __false_type has_trivial_default_constructor; typedef __false_type has_trivial_copy_constructor; typedef __false_type has_trivial_assignment_operator; typedef __false_type has_trivial_destructor; typedef __false_type is_POD_type; };
从上面的定义可看出: __type_traits里面的类型都不是从T里面获取。那么,既然__type_traits里面的类型都不是从T里面获取,那么如何通过__type_traits获取不同type的信息呢?
办法是,只能通过对__type_traits进行特化或偏特化。如果你自定义了一个类型K,而不针对类型K进行特化,__type_traits<K>里面的类型都是默认的类型。
SGI STL内部对C++内置类型都进行了特化处理。比如:
template <> struct __type_traits<char> { typedef __true_type has_trivial_default_constructor; typedef __true_type has_trivial_copy_constructor; typedef __true_type has_trivial_assignment_operator; typedef __true_type has_trivial_destructor; typedef __true_type is_POD_type; };