Create a constant iterator and a non-constant iterator

I am writing an iterator class (say MyIterator) for a library.

Is it good to use const overloading to create const MyIteratoracts like a const_iteratorof std::vector, but MyIteratoracts like iteratorof std::vector?

Will the user / developer of the library be confused?

The implementation will look like this:

// std::iterator example
#include <iostream>     // std::cout
#include <iterator>     // std::iterator, std::input_iterator_tag

class MyIterator : public std::iterator<std::input_iterator_tag, int>
{
  mutable int* p;
public:
  MyIterator(int* x) :p(x) {}
  MyIterator(const MyIterator& mit) : p(mit.p) {}
  MyIterator& operator++() {++p;return *this;}
  MyIterator operator++(int) {MyIterator tmp(*this); operator++(); return tmp;}
  bool operator==(const MyIterator& rhs) {return p==rhs.p;}
  bool operator!=(const MyIterator& rhs) {return p!=rhs.p;}
  const int& operator*() const {return *p;} // <-- const overload
  int& operator*() {return *p;}
};

An alternative would be to use patterns to implement a single iterator class, which can be specialized in constant and non-constant iterators. I am currently doing this (I heard that boost does this ...). But patterns get complex very quickly when I implement a range, and then a range range (as in a nested range, based on a loop).

+4
1

const MyIterator const_MyIterator (const_iterator) , const_iterator , , , .

, const MyIterator , ++ --, , .

, - const_iterator, .

/ ?

, : , , - ( ) const iterator vs const_iterator.

+7

Source: https://habr.com/ru/post/1659848/


All Articles