- struct __true_type {
- };
- struct __false_type {
- };
- template <class _Tp>
- 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;
- };
- template <class _Tp>
- struct __type_traits<_Tp*> {
- 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;
- };
在STL里面的stl_iterator_base.h头文件里,用到了iterator traits技术的有两个函数,advance和distance。前面看到type traits在constuct和destory里的使用,现在来看看advance函数:
- template <class _InputIter, class _Distance>
- inline void __advance(_InputIter& __i, _Distance __n, input_iterator_tag) {
- while (__n--) ++__i;
- }
- template <class _BidirectionalIterator, class _Distance>
- inline void __advance(_BidirectionalIterator& __i, _Distance __n,
- bidirectional_iterator_tag) {
- __STL_REQUIRES(_BidirectionalIterator, _BidirectionalIterator);
- if (__n >= 0)
- while (__n--) ++__i;
- else
- while (__n++) --__i;
- }
- template <class _RandomAccessIterator, class _Distance>
- inline void __advance(_RandomAccessIterator& __i, _Distance __n,
- random_access_iterator_tag) {
- __STL_REQUIRES(_RandomAccessIterator, _RandomAccessIterator);
- __i += __n;
- }
- template <class _InputIterator, class _Distance>
- inline void advance(_InputIterator& __i, _Distance __n) {
- __STL_REQUIRES(_InputIterator, _InputIterator);
- __advance(__i, __n, iterator_category(__i));
- }
- template <class _Tp, class _Distance>
- inline input_iterator_tag
- iterator_category(const input_iterator<_Tp, _Distance>&)
- { return input_iterator_tag(); }
- inline output_iterator_tag iterator_category(const output_iterator&)
- { return output_iterator_tag(); }
- template <class _Tp, class _Distance>
- inline forward_iterator_tag
- iterator_category(const forward_iterator<_Tp, _Distance>&)
- { return forward_iterator_tag(); }
- template <class _Tp, class _Distance>
- inline bidirectional_iterator_tag
- iterator_category(const bidirectional_iterator<_Tp, _Distance>&)
- { return bidirectional_iterator_tag(); }
- template <class _Tp, class _Distance>
- inline random_access_iterator_tag
- iterator_category(const random_access_iterator<_Tp, _Distance>&)
- { return random_access_iterator_tag(); }
traits就是个好东西啊,比起if-else好多了。神奇的技术。