From my background in Java I am familiar with generic data types but I am not used to the c++ syntax yet.
I wrote the most basic implementation of a circular buffer
template <class T> class RingBuffer{
public :
RingBuffer(int capacity);
void add(T value);
T peekLifo(int index); //Index 0 newest added item....
T poll();
private :
int capacity;
int currentIndex; //Index of the last added item
T values[]; //Array to save values
int calculateIndexLifo(int index); // index shifted to the left of the last added item.
};
template <class T>
RingBuffer<T>::RingBuffer(int capacity){
this.capacity = capacity;
values = new T[capacity];
}
template<class T>
int RingBuffer<T>::calculateIndexLifo(int index){
//Do we need to wrap the index around?
if(currentIndex - index >= 0) {
return currentIndex-index;
} else{
//we need to wrap around (maybe multiple times). TODO test implementation
return calculateIndexLifo(currentIndex - (index%capacity));
}
}
template <class T>
void RingBuffer<T>::add(T value){
//Wrap around if we are out of bounds
if( (currentIndex + 1) > capacity){
currentIndex = 0;
}
values[currentIndex] = value;
currentIndex++;
}
template <class T>
T RingBuffer<T>::peekLifo(int index){
return values[calculateIndexLifo(index)];
}
//---
RingBuffer<long> s1RevEvents = new RingBuffer<long>(5) ;
Trying to create an object falis with the following error message:
"warning: invalid conversion from 'RingBuffer*' to 'int' [-fpermissive] RingBuffer s1RevEvents = new RingBuffer(5) ;".
Without object creation the code compiles just fine. Where did In go wrong and why does the compiler talk about long and int?
An unrelated second question regarding baud rates. What happens if I want to send more data than my current rate supports? e.g. a loop with only serial.print(0) in it. Is there a stack in the background which will try to send all the cached values on best effort basis or will too much data be discarded? I am asking because I don't want my sensor data to eventually start to lag if the application is running for some time.
Edit: There is most likely a simple index error as currentIndex actually points to the next free space. But this is not really the issue here