fredoverflow
fredoverflow

Reputation: 263078

Generating member types for containers

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?

Upvotes: 4

Views: 167

Answers (3)

decltype
decltype

Reputation: 1601

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.

Upvotes: 1

Tristram Gr&#228;bener
Tristram Gr&#228;bener

Reputation: 9711

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

Upvotes: 0

sbi
sbi

Reputation: 224039

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.

Upvotes: 0

Related Questions