Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to wrap iterator of boost::circular_buffer?

I’m trying to use boost::circular_buffer to manage fixed size of the queue.

To do that, I wrap boost::circular_buffer by using class Something.

class Something {
  public:
    Something();
  private:
    boost::circular_buffer<int> buffer;
};

Here, the problem is that class Something should wrap iterator of buffer.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For example, If I use std::vector<int>, it is simple:

class Something {
  public:
    Something();
    typedef std::vector<int>::iterator Iterator;
    
    Iterator begin() { return buffer.begin(); }
    Iterator end() { return buffer.end(); }
    ...
  private:
    std::vector<int> buffer;
};

How to use boost::circular_buffer to handle this?

>Solution :

You can do the exact same thing as you do with the std::vector.

typedef std::vector<int>::iterator Iterator; declares a local type called Iterator that is an alias for std::vector<int>‘s iterator type.

So logically, you should be able to just swap out the std::vector<int> for a boost::circular_buffer<int> and it should just drop in:

#include <boost/circular_buffer.hpp>

class Something {
  public:
    Something();

    typedef boost::circular_buffer<int>::iterator Iterator;
    
    Iterator begin() { return buffer.begin(); }
    Iterator end() { return buffer.end(); }

  private:
    boost::circular_buffer<int> buffer;
};

You can clean this up further a bit by using a second type alias for the container itself. This way, you can change the container type by altering a single line of code, and everything else flows from there.

#include <boost/circular_buffer.hpp>

class Something {
  public:

    Something();

    using container_type = boost::circular_buffer<int>;
    using Iterator = container_type::iterator;
    
    Iterator begin() { return buffer.begin(); }
    Iterator end() { return buffer.end(); }

  private:
    container_type buffer;
};

N.B. I used using instead of typedef since it’s generally considered easier to read in modern code, but the meaning is the same.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading