Item 47:使用Traits类提供类型信息
Posted harttle
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Item 47:使用Traits类提供类型信息相关的知识,希望对你有一定的参考价值。
template<typename IterT, typename DistT>
void advance(IterT& iter, DistT d); // 如果d小于0,就逆向移动
STL迭代器回顾
Tag 结构体
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<typename IterT, typename DistT>
void advance(IterT& iter, DistT d)
if (iter is a random access iterator)
iter += d; // use iterator arithmetic
// for random access iters
else
if (d >= 0) while (d--) ++iter; // use iterative calls to
else while (d++) --iter; // ++ or -- for other
// iterator categories
Traits
template<typename IterT> // template for information about
struct iterator_traits; // iterator types
用户类型的迭代器
template < ... > // template params elided
class deque
public:
class iterator
public:
typedef random_access_iterator_tag iterator_category;
:
;
template<typename IterT>
struct iterator_traits
typedef typename IterT::iterator_category iterator_category;
;
基本数据类型的指针
template<typename IterT> // partial template specialization
struct iterator_traits<IterT*>
typedef random_access_iterator_tag iterator_category;
;
advance的实现
template<typename IterT, typename DistT>
void advance(IterT& iter, DistT d)
if (typeid(typename std::iterator_traits<IterT>::iterator_category) ==
typeid(std::random_access_iterator_tag))
...
template<typename IterT, typename DistT>
void advance(IterT& iter, DistT d)
doAdvance( // call the version
iter, d, // of doAdvance
typename std::iterator_traits<IterT>::iterator_category()
);
// 随机访问迭代器
template<typename IterT, typename DistT>
void doAdvance(IterT& iter, DistT d, std::random_access_iterator_tag)
iter += d;
// 双向迭代器
template<typename IterT, typename DistT>
void doAdvance(IterT& iter, DistT d, std::bidirectional_iterator_tag)
if (d >= 0) while (d--) ++iter;
else while (d++) --iter;
// 输入迭代器
template<typename IterT, typename DistT>
void doAdvance(IterT& iter, DistT d, std::input_iterator_tag)
if (d < 0 )
throw std::out_of_range("Negative distance"); // see below
while (d--) ++iter;
本文地址:http://harttle.com/2015/09/15/effective-cpp-47.html
以上是关于Item 47:使用Traits类提供类型信息的主要内容,如果未能解决你的问题,请参考以下文章
C++ STL应用与实现19: 迭代器特性-iterator traits
STL源码剖析——Iterators与Traits编程#5 __type_traits
对于既不是 X<A, T...> 也不是成员 typedef element_type 的类型,pointer_traits 提供了啥?