2016-07-06 6 views
-1

Ich will eine bedingte printf, so etwas wie dieseWie erstellt man einen Wrapper auf printf?

class ConditionalPrintf 
{ 
public: 
    ConditionalPrintf(bool print) 
     : print_(print) 
    {} 

    void printf(int x, double y, char b, const char* format, ...) const 
    { 
     // use x, y and b 

     va_list argptr; 
     va_start(argptr, format); 

     if (print_) 
      printf(format, argptr); 

     va_end(argptr); 
    } 

private: 
    bool print_; 
}; 

Aber er druckt Unsinn schreiben. Ist irgendwas falsch? Kann dieser Parameter implizit Dinge verändern?

Auch, wenn das keine gute Idee ist, welche anderen Lösungen gibt es? Ich möchte einfach nicht if (print) printf(...) Milliarden Male schreiben.

+0

einen Blick auf vprintf haben: http://en.cppreference.com/w/cpp/io/c/vfprintf –

+0

Nein, ich will nicht benutze es, ich muss verstehen, was mit meinem Programm nicht stimmt. –

+1

Was mit Ihrem Programm nicht stimmt, ist, dass Sie es nicht verwenden. Es wurde entwickelt, um eine va_list in printf weiterzuleiten! –

Antwort

0

vprintf vorwärts die ARG Liste printf

#include <stdio.h> 
#include <stdarg.h> 

class ConditionalPrintf 
{ 
public: 
    ConditionalPrintf(bool print) 
     : print_(print) 
    {} 

    void printf(int x, double y, char b, const char* format, ...) const 
    { 
     // use x, y and b 

     va_list argptr; 
     va_start(argptr, format); 

     if (print_) 
      vprintf(format, argptr); 

     va_end(argptr); 
    } 

private: 
    bool print_; 
};