开发者

Generating member types for containers

开发者 https://www.devze.com 2023-02-13 08:57 出处:网络
When I define my own containers, I have to provide a dozen of member types, for example: typedef T& reference;

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?


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消