2017-11-16 10 views
-1

간단한 인쇄 기능으로 템플릿 기반 버퍼 클래스가 있습니다.데이터 형식에 따른 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?

+1

그것은'std :: cout'과 같은 C++ 스트림에 대한 좋은 점 중 하나입니다.'p와 같은 고정 형식 지정자없이 다른 유형을 처리 할 수 ​​있습니다. 린트. 즉, C++에서'printf'를 사용하지 마십시오. –

+0

@Someprogrammerdude 나는 정확한 충돌을 기억하지 못한다. 그러나'#include '은 코드의 다른 부분을 깨뜨 렸고, 그래서 나는'printf'를 사용하고있다. – Mike

+0

그러면 너는하지 말아야 할 일을하고있다. 새로운 질문에서 그 문제에 대해 물어야합니다. –

답변

1

다른 의견에 언급 된대로 std::cout에는 모든 기본 제공 유형에 대한 오버로드가 있어야합니다. 당신이 정말로 printf를 사용하여 주장하는 경우, 다음과 같은 해킹을 시도 할 수 있습니다 :

#include <typeinfo> // for typeid 

std::string printfCmd("I wish to print this: "); 
// int myVar = 69; // uncomment to change var type to int 
char myVar = 'd'; 
if (typeid(int) == typeid(myVar)) { 
    printfCmd += "%d"; 
} else if (typeid(char) == typeid(myVar)) { 
    printfCmd += "%c"; 
} else { 
    // some warning/error 
} 

printf(printfCmd.c_str(), myVar); 

그것은 좋은 해결책이 아닌, 당신이 정말로에있는 경우에만 사용하십시오. 당신은 C++ 오버로드 된 삽입 연산자를 사용하지 않으려면

0

, 당신은 당신의 자신의 오버로드 된 함수를 작성할 수 있습니다

void print(int i) { 
    printf("%4d",i); 
} 

void print(double d) { 
    printf("%8g",d); 
} 

이제

필요로 할 때 당신이 당신의 printBuff 함수에서 print를 호출 할 수 있습니다 :

printf("bufferValues["%2d] =",ii); 
print(bufferValues[ii]); 
printf("\n");