1

I have a legacy Buffer class and iterator for it (I use Visual Studio 2013 - Windows XP v120_xp toolset, so I suppose I use c++11 standard):

template <typename T>
class PtrIterator : public std::iterator<std::forward_iterator_tag, T> {
    typedef PtrIterator<T> iterator;
    pointer pos_;

public:
    PtrIterator() : pos_(nullptr) {}
    explicit PtrIterator(T* v) : pos_(v){}
    ~PtrIterator() = default;

    iterator operator++(int)  // postfix
    { return pos_++; }
    iterator& operator++()  // prefix
    {
        ++pos_;
        return *this;
    }
    reference operator*() const
    { return *pos_; }
    pointer operator->() const
    { return pos_; }
    iterator operator+(difference_type v) const
    { return pos_ + v; }
    bool operator==(const iterator& rhs) const
    { return pos_ == rhs.pos_; }
    bool operator!=(const iterator& rhs) const
    { return pos_ != rhs.pos_; }
};

using BufferIterator = PtrIterator<uint8_t>;

class Buffer{
public:
    // ...
    BufferIterator begin() const;
    BufferIterator end() const;
}

Now I'm wonder, if it possible to get rid of custom iterator and use standard one. I'm trying to do the following thing:

using BufferIterator = std::iterator<std::random_access_iterator_tag, uint8_t, ptrdiff_t, uint8_t*, uint8_t&>;

Compiler says there are no operators for BufferIterator, such as operator== and so on. But I don't know how such declarations looks like (note, that my classes are in a namespace). I tried the following one:

bool operator!=(const og::BufferIterator& lhs, const og::BufferIterator& rhs)
{ return false; }

, but that doesn't work.

So, how to fit standard iterator for my needs?

qloq
  • 689
  • 1
  • 5
  • 15
  • `std::iterator` was deprecated in C++17. IIRC the "modern way" is to write your own iterator type: https://stackoverflow.com/questions/43268146/why-is-stditerator-deprecated – NathanOliver Jun 15 '22 at 14:59
  • 1
    Just return the pointer itself (`using BufferIterator = uint8_t*;`)? There the only good reason I see for not using this would be debugging which would also become significantly harder, if you use some default provided by the standard library. – fabian Jun 15 '22 at 15:00
  • 1
    `std::iterator` has zero data members and zero member functions. It existed to "simplify" defining all the member types required by the [*Iterator*](https://en.cppreference.com/w/cpp/named_req/Iterator) named-requirement. – Caleth Jun 15 '22 at 15:51
  • Another option could be to implement the buffer with a `std::vector` and use its iterators. – sigma Jun 16 '22 at 01:19

0 Answers0