I've a class that owns a std::vector and should provide begin(), end(), cbegin() and cend() methods. Since I don't want to expose implementation details, i.e. that I use a std::vector, I must have my own Iterator. As I understood, this is what boost::iterator_adapter is for: It takes some iterator and wraps it up within a new Iterator type -> my std::vector<T>::iterator becomes then MyClass::iterator.

First of all, is my understanding of boost::iterator_adapter correct and second can I avoid having to write a second const_iterator and instead e.g. typedef it (using const_iterator = const iterator)?

    class MyClass {
    public:
        iterator begin();
        // ...
    private:
        using container_t = std::vector;
        container_t<int> container;
    }

    class MyClass::iterator
      : public boost::iterator_adaptor<
            MyClass::iterator                     // Derived
          , container_t<int>::iterator            // Base
          , boost::use_default                    // Value
          , boost::random_access_traversal_tag >  // CategoryOrTraversal
    {
     public:
        iterator()
          : iterator::iterator_adaptor_() {}
        explicit iterator(const iterator::iterator_adaptor_::base_type& p)
          : iterator::iterator_adaptor_(p) {}
     private:
        friend class boost::iterator_core_access;
    };

this might not compile.

1

There are 1 best solutions below

0
On

No, you can't use something like: using const_iterator = const iterator.

A const_iterator works like a T const *. A const iterator works like a T * const.

That is, what you want is an iterator that can be modified to point to other objects, but provides read-only access to those objects. What const iterator will give you is, instead, an iterator that can't itself be modified, but gives read/write access to the object to which it refers.