Re: Ring Buffer & templates
Thanks to the suggestions received here now it works pretty well!
It's here below, if you see anything not nice please tell me...
I was now wondering what could be best to do to allow iteration on the
subclasses.
I could
- make "buffer" a protected variable, so in the subclass I can access directly
- just wrap the size method (as I do now) do use the normal for (int
i..) construct
Is there even a better way?
And if I got with a templated class I can't write the implementation in
another file, but why?
Before I had also a
"T pop();" function, and if I tried to make it virtual it didn't work at
all.
Maybe theoretically it's just wrong to make pop/push virtual since those
should work everywhere in the same way, right?
Thanks
--8<---------------cut here---------------start------------->8---
#ifndef RINGBUFFER_H
#define RINGBUFFER_H
#include <deque>
template<typename T>
class RingBuffer
{
// TODO: see how to make it also iterable
private:
size_t max_size;
std::deque<T> buffer;
public:
RingBuffer(size_t max_size);
void push(T el);
size_t size() { return buffer.size(); }
T operator[](int index) { return buffer[index]; }
// TODO: move in the implementation below if possible
friend ostream& operator<<(ostream& s, const RingBuffer<T>& c) {
s << c;
return s;
}
};
template<typename T>
RingBuffer<T>::RingBuffer(size_t max_size) : max_size(max_size)
{}
template<typename T>
void RingBuffer<T>::push(T el)
{
if (buffer.size() == max_size) {
buffer.pop_front();
}
buffer.push_back(el);
}
#endif /* RINGBUFFER_H */
--8<---------------cut here---------------end--------------->8---