Can 'iterator' type just subclass 'const_iterator'?

前端 未结 3 1076
谎友^
谎友^ 2021-01-01 19:54

After another question about iterators I\'m having some doubts about custom containers. In my container, iterator is a subclass of const_iterator,

3条回答
  •  暖寄归人
    2021-01-01 20:14

    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 iterator_base;
    
    typedef iterator_base iterator;
    typedef iterator_base 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".

提交回复
热议问题