我是一名学生,试图从头开始与STL一起工作。现在我的任务是实现迭代器。是的,我知道它正在重新发明轮子,但它会帮助我更好地理解它们的工作原理以及如何应用它们。希望人们可以指出我的实现过于简单化还是缺少任何东西。
// ptrdiff_t
#include <cstddef>
template <class Category, class T, class Distance = ptrdiff_t,
class Pointer = T*, class Reference = T&>
struct iterator
{
typedef T value_type;
typedef Distance difference_type;
typedef Pointer pointer;
typedef Reference reference;
typedef Category iterator_category;
};
template <class Iterator> class iterator_traits
{
typedef typename Iterator::different_type difference_type;
typedef typename Iterator::value_type value_type;
typedef typename Iterator::pointer pointer;
typedef typename Iterator::reference reference;
typedef typename Iterator::iterator_category iterator_category;
};
struct random_access_iterator_tag { };
template <class T> class iterator_traits<T*>
{
typedef ptrdiff_t difference_type;
typedef T value_type;
typedef T* pointer;
typedef T& reference;
typedef random_access_iterator_tag iterator_category;
};
namespace detail
{
template <class InputIterator>
void foo(InputIterator& i, random_access_iterator_tag)
{
}
}
template <class InputIterator>
void foo(InputIterator& i)
{
typename iterator_traits<InputIterator>::iterator_category category;
detail::foo(i, category);
}