In this implementation, the TBuffer class is a template class that can be instantiated with different types (int, double, std::string) and different sizes (N).
#include <iostream>
#include <stdexcept>
template <typename T, int N>
class TBuffer {
private:
T buffer[N];
T nullValue;
public:
TBuffer(T nullValue) : nullValue(nullValue) {
// Initialize the buffer with null values
for (int i = 0; i < N; ++i) {
buffer[i] = nullValue;
}
}
void addElement(const T& element, int index) {
if (index < 0 || index >= N) {
throw std::out_of_range("Index out of range");
}
buffer[index] = element;
}
T getElement(int index) const {
if (index < 0 || index >= N) {
throw std::out_of_range("Index out of range");
}
return buffer[index];
}
T sum() const {
T result = nullValue;
for (int i = 0; i < N; ++i) {
result += buffer[i];
}
return result;
}
bool isEmpty() const {
for (int i = 0; i < N; ++i) {
if (buffer[i] != nullValue) {
return false;
}
}
return true;
}
};