I was asked to implement a circular buffer that takes an unspecified type in C++. I assume the generic type to be of primitive type. (or should it consider non-primitive types?) For the buffer, I am using a basic array, e.g. T[] with new and delete to initialize and destroy it.
I have implemented the buffer class and tested it on integers with the expected output. But it does not work on std::string
. The problem is that, when I pop the buffer, I clear the element by setting it to zero, and the compiler complains that doing so is ambiguous. As such, I need a generic way to clear an element, and I thought the std::array
might support this feature, but I cannot find it in the documentation.
Is there a generic way to clear an element in a std::array or basic array, or is std::allocator my only option? Or, if I am completely in the wrong direction, How should I implement the pop method to reset the first element and increment the front index to that of the next element?
Thanks in advance!
In case it helps, below is my related code:
template<class T> T CircularBuffer<T>::pop_front()
{
if (_size == 0)
return 0;
T value = buffer[_front];
buffer[_front] = 0;
if (--_size == 0)
{
_front = -1;
_back = -1;
}
else
{
_front = (_front + 1) % _capacity;
}
return value;
}