Home > Enterprise >  How to wrap iterator of boost::circular_buffer?
How to wrap iterator of boost::circular_buffer?

Time:04-13

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.

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?

CodePudding user response:

If all you need is begin and end, you can simply use auto return type (or decltype(auto) for general case)

class Something {
  public:
    Something();
    auto begin() { return buffer.begin(); }
    auto end() { return buffer.end(); }
  private:
    boost::circular_buffer<int> buffer;
};

CodePudding user response:

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.

  • Related