Rella
Rella

Reputation: 66945

Boost Circular Buffer, how to make it call some function when it is filled?

I like Boost Templated Circular Buffer Container, but how to get when it was filled 100%?

   #include <boost/circular_buffer.hpp>

   int main() {

      // Create a circular buffer with a capacity for 3 integers.
      boost::circular_buffer<int> cb(3);

      // Insert some elements into the buffer.
      cb.push_back(1);
      cb.push_back(2);
      cb.push_back(3);

      // Here I want some function to be called (for example one that would cout all buffer contents)

      int a = cb[0];  // a == 1
      int b = cb[1];  // b == 2
      int c = cb[2];  // c == 3

      return 0;
   }

So how to listen for such event in boost::circular_buffer and for example cout all buffer contents?

Upvotes: 1

Views: 4802

Answers (2)

In silico
In silico

Reputation: 52159

You can wrap the circular_buffer instance into its own class and implement event handling on top of it.

class MyCircularBuffer
{
public:
    MyCircularBuffer() : buffer(3) {}

    void PushBack(int i)
    {
        buffer.push_back(i);
        if(buffer.size() == 3)
        {
            // buffer is full!
        }
    }
private:
    boost::circular_buffer<int> buffer;
};

If code outside of MyCircularBuffer needs to be notified of the event, you can implement some variant of the Observer pattern, use Boost.Function or use some other callback mechanism.

Upvotes: 3

Nicol Bolas
Nicol Bolas

Reputation: 473447

It doesn't fire an event. You must manually check to see if it is full each time you add to it, and if it is, then you execute some process.

This would typically be done by wrapping the container in a user-created object, so that you can monitor additions to the buffer.

Or, to put it another way, you don't need a generic solution; just write an object that uses the container and flushes it automatically.

Upvotes: 1

Related Questions