c++inheritanceiteratorrange-checking

Extending iterators in C++


I'm trying to implement an iterator which encapsulates another iterator and performs range checking. Therefore I'm extending from that Iterator like so:

 template<typename ITERATOR_T>
 class r_iterator : public ITERATOR_T {

     //...

     r_iterator (ITERATOR_T begin, ITERATOR_T end) {
         this->begin = begin;
         this->end = end;
    }
 };

I want to use the iterators that are passed in the constructor to perform the range checking. My idea is to set the thing to which the "this"-iterator (i.e. r_iterator) points to to the element which is pointed to by the "begin" iterator from the constructor. This I would like to do so I can override certain methods like operator++ for example, perform range checking and then call the super method of the class I'm extending.

I would thus like to know whether it is possible to somehow set the element the "this"-iterator (r_iterator) points to assuming that I'm extending some STL Iterator class.

I could unfortunately not find any information about that in the c++ reference.

Regards and Thank you


Solution

  • There's no need to inherit, you can write a simple wrapper class like this:

    #include <iostream>
    #include <vector>
    #include <stdexcept>
    
    template <typename Iterator>
    class MyIterator
    {
        Iterator _begin;
        Iterator _end;
        Iterator _cur;
    public:
        explicit MyIterator(Iterator begin, Iterator end)
            : _begin(begin), _end(end)
        {
            _cur = _begin;
        }
    
        bool has_next() const 
        {
            return (_cur != _end);
        }
    
        void operator++(int dummy) 
        { 
            if (!has_next())
                throw std::out_of_range("Out of range.");
            _cur++;
        }
    };
    
    int main(int argc, char* argv[]) 
    {
        std::vector<int> v = {1, 2, 3};
        MyIterator<std::vector<int>::iterator> my_it(v.begin(), v.end());
        my_it++;
        my_it++;
        my_it++;
        my_it++;
        return 0;
    }