Formation of element types for containers

When I define my own containers, I have to provide a dozen 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 that I inherit that looks like std::iterator<T> for my own iterators?

+4
source share
3 answers

There is boost :: iterator for this specific task.

Hope this tutorial becomes clear http://www.boost.org/doc/libs/1_46_0/libs/iterator/doc/iterator_facade.html#tutorial-example

0
source

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

 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 it. In the standard library, std::allocator defines all of these typedefs, so inheriting from it will technically do what you wanted, and should not impose any overhead at runtime. I still think it's best to just write your own typedefs.

+1
source

Is there a base class template that I can inherit that looks like std::iterator<T> for my own iterators?

No, but thatโ€™s a good idea. OTOH, it would be more difficult to refer to these types from within the container, since they would be identifiers in the base class, depending on the template parameters of the derived class. This can be a nuisance.

0
source

Source: https://habr.com/ru/post/1341145/


All Articles