4

When I define my own containers, I have to provide a dozen of member types, for example:

    typedef T& reference;
    typedef const T& const_reference;
    typedef T* iterator;
    typedef const T* const_iterator;
    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;
    typedef T value_type;
    typedef T* pointer;
    typedef const T* const_pointer;
    typedef std::reverse_iterator<iterator> reverse_iterator;
    typedef std::reverse_iterator<const_iterator> const_reverse_iterator;

Is there a base class template I can inherit from, similar to std::iterator<T> for my own iterators?

fredoverflow
  • 256,549
  • 94
  • 388
  • 662

3 Answers3

1

If you need to do this often, then I guess you could create a

template<typename T>
struct container
{
    typedef T& reference;
    typedef const T& const_reference;
    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;
    typedef T value_type;
    typedef T* pointer;
    typedef const T* const_pointer;
};

And inherit from this. In the standard library, std::allocator does define all those typedefs, thus inheriting from it would technically do what you wanted and should not impose any runtime overhead. I still think it's better to just write your own typedefs, though.

decltype
  • 1,591
  • 8
  • 12
0

Is there a base class template I can inherit from, similar to std::iterator<T> for my own iterators?

No, but it's a nice idea. OTOH, it would make it harder to refer to these types from within the container, because they'd be identifiers in a base class dependent on the derived class' template parameters. That can become a nuisance.

sbi
  • 219,715
  • 46
  • 258
  • 445
0

There is boost::iterator for this specific need.

I hope this tutorial will make things clear http://www.boost.org/doc/libs/1_46_0/libs/iterator/doc/iterator_facade.html#tutorial-example

Tristram Gräbener
  • 9,601
  • 3
  • 34
  • 50