I have a templated buffer class with a simple printing function.
template <typename valueType, typename sumType, int N>
class IM_buffer
{
public:
IM_buffer()
: bufferValues(), numValues(-1), currentSum() { }
void record(valueType sample)
{
// Set buffer index to be recorded
numValues++;
// Get memory location for oldest element in buffer
valueType& oldest = bufferValues[modIdx(numValues)];
// Add the input value to the current sum and take away the value being replaced
currentSum += sample - oldest;
// And now do the actual replacement in the same memory location
oldest = sample;
}
valueType getCurrent() { return bufferValues[modIdx(numValues)]; }
valueType getNthPrev(int Nprev) { return bufferValues[modIdx(numValues-Nprev)]; }
sumType getCurrentSum() { return currentSum; }
double getAvg() { return (double) currentSum / MIN(numValues+1, N); }
int getNumValues() { return numValues+1; }
int getBufferSize() { return N; }
void printBuff()
{
for (int ii=0; ii<N; ii++)
{
// if it's an integer type I need:
printf("bufferValues[%2d]=%4d\n",ii,bufferValues[ii]);
// but if it's a floating point type I need:
printf("bufferValues[%2d]=%8g\n",ii,bufferValues[ii]);
}
}
void clear()
{
for (int ii=0; ii<N; ii++)
bufferValues[ii] = (valueType) 0.0;
numValues = 0;
currentSum = (sumType) 0.0;
}
private:
valueType bufferValues[N];
int numValues;
sumType currentSum;
int modIdx(int a) { return (a % N + N) % N; }
};
However, the format string of the printf
should depend on what the data type is (e.g. int, vs. float, vs double). I've seen discussions like this but I don't really want to print out the data type, I just need to change the printf
format string based on the data type. Can anyone point me in the right direction for how to implement some condition logic to select the right printf
?