Created
October 28, 2010 18:07
-
-
Save AndreaCrotti/651951 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef RINGBUFFER_H | |
#define RINGBUFFER_H | |
// when I don't do any new do I still need a destructor? | |
// check how can I pass functions to execute inside it | |
// things should be as functional as possible | |
#define SUM(x, y) ((x + y) % max_size) | |
#define NEXT_POS(x) SUM(x, 1) | |
#include <vector> | |
#include <iostream> | |
using namespace std; | |
// can keep in the buffer a type T | |
template<typename T> | |
class RingBuffer | |
{ | |
private: | |
int start, end; | |
size_t max_size; | |
std::vector<T> buffer; | |
public: | |
RingBuffer(size_t max_size); | |
void add(T el); | |
T get(); | |
const T operator[](int index) const; | |
}; | |
template<typename T> | |
RingBuffer<T>::RingBuffer(size_t max_size) : max_size(max_size), start(0), end(0) | |
{ | |
buffer.resize(max_size); | |
} | |
template<typename T> | |
const T RingBuffer<T>::operator[](int index) const | |
{ | |
return buffer[SUM(start, index)]; | |
} | |
template<typename T> | |
void RingBuffer<T>::add(T el) | |
{ | |
buffer[end] = el; | |
end = NEXT_POS(end); | |
if (end == start) | |
++start; | |
} | |
template<typename T> | |
T RingBuffer<T>::get() | |
{ | |
return buffer[start]; | |
} | |
// in case I want to print the object I can think that is printable | |
#endif /* RINGBUFFER_H */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment