W
W
Wiki-fan2015-11-06 21:38:58
C++ / C#
Wiki-fan, 2015-11-06 21:38:58

How to make const_iterator without code duplication?

Can this be done? I wrote my own iterator inheriting from

public std::iterator<std::random_access_iterator_tag, T>
, implemented everything I needed, and now I want a const_iterator without rewriting it all.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
Wiki-fan, 2015-11-07
@Wiki-fan

I ended up writing something like this:

template<bool is_const_iterator>
  class CMetaIterator : public std::iterator<std::random_access_iterator_tag, T> {

  public:
    typedef T value_type;
    typedef typename std::conditional<is_const_iterator, const value_type&, value_type&>::type reference;
    typedef typename std::conditional<is_const_iterator, const value_type*, value_type*>::type pointer;
  ...
  reference operator*() const;
  pointer operator->() const;
  ...
};
  typedef CMetaIterator<false> CIterator;
  typedef CMetaIterator<true> CConstIterator;
  typedef std::reverse_iterator<CIterator> CReverseIterator;
  typedef std::reverse_iterator<CConstIterator> CReverseConstIterator;

A
Armenian Radio, 2015-11-06
@gbg

Look at Myers, it's described there.
The idea is to use a const method call and const_cast<> in a non-const method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question