How do you create a debug only function that takes a variable argument list? Like printf()

后端 未结 14 2158
心在旅途
心在旅途 2020-12-23 09:44

I\'d like to make a debug logging function with the same parameters as printf. But one that can be removed by the pre-processor during optimized builds.

<
14条回答
  •  失恋的感觉
    2020-12-23 10:16

    In C++ you can use the streaming operator to simplify things:

    #if defined _DEBUG
    
    class Trace
    {
    public:
       static Trace &GetTrace () { static Trace trace; return trace; }
       Trace &operator << (int value) { /* output int */ return *this; }
       Trace &operator << (short value) { /* output short */ return *this; }
       Trace &operator << (Trace &(*function)(Trace &trace)) { return function (*this); }
       static Trace &Endl (Trace &trace) { /* write newline and flush output */ return trace; }
       // and so on
    };
    
    #define TRACE(message) Trace::GetTrace () << message << Trace::Endl
    
    #else
    #define TRACE(message)
    #endif
    

    and use it like:

    void Function (int param1, short param2)
    {
       TRACE ("param1 = " << param1 << ", param2 = " << param2);
    }
    

    You can then implement customised trace output for classes in much the same way you would do it for outputting to std::cout.

提交回复
热议问题