Answer the question
In order to leave comments, you need to log in
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
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;
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 questionAsk a Question
731 491 924 answers to any question