Can 'iterator' type just subclass 'const_iterator'?

不羁岁月 提交于 2019-11-30 11:29:53

Yes, this is fine. This is how VC10's implementation of the iterators for vector are structured, for example. See _Vector_iterator and _Vector_const_iterator in <vector>.

By the way, writing iterators is hard. It's worth your time to learn and use the boost::iterator library.

Subclassing seems strange to me here, but there is effectively an issue.

Even if you don't want to depend on Boost parts, check the Boost.Iterator library, and more especially the iterator_facade and iterator_adaptor bits.

There is a full-blown example of how to write an iterator and a const_iterator for your class without duplicating too much. Their idea is to write a template iterator_base class which you can then use for const and non-const types in the line of:

template <class Value> class iterator_base;

typedef iterator_base<T> iterator;
typedef iterator_base<const T> const_iterator;

The issue with subclassing is that you should then provide a virtual destructor and you're exposed to slicing (when building a const_iterator from an iterator)

So, unlike others here, I don't find it "fine".

Think about a case which will require you to modify the iterator's members.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!