간단한 인쇄 기능으로 템플릿 기반 버퍼 클래스가 있습니다.데이터 형식에 따른 printf 형식
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; }
};
그러나 printf
의 형식 문자열 데이터 유형 (예를 들어, INT, 플로트 대, 이중 대)이 무엇인지에 의존한다. this과 같은 토론을 보았습니다. 그러나 실제로 데이터 유형을 인쇄하고 싶지는 않습니다. 데이터 유형에 따라 printf
형식 문자열을 변경해야합니다. 누구든지 오른쪽을 선택하는 몇 가지 조건 논리를 구현하는 방법에 대한 올바른 방향으로 나를 가리킬 수 printf
?
그것은'std :: cout'과 같은 C++ 스트림에 대한 좋은 점 중 하나입니다.'p와 같은 고정 형식 지정자없이 다른 유형을 처리 할 수 있습니다. 린트. 즉, C++에서'printf'를 사용하지 마십시오. –
@Someprogrammerdude 나는 정확한 충돌을 기억하지 못한다. 그러나'#include'은 코드의 다른 부분을 깨뜨 렸고, 그래서 나는'printf'를 사용하고있다. –
Mike
그러면 너는하지 말아야 할 일을하고있다. 새로운 질문에서 그 문제에 대해 물어야합니다. –