How does QDebug() << stuff; add a newline automatically?

前端 未结 4 1640
挽巷
挽巷 2020-12-30 05:11

I\'m trying to implement my own qDebug() style debug-output stream, this is basically what I have so far:

struct debug
{
#if defined(DEBUG)
             


        
4条回答
  •  别那么骄傲
    2020-12-30 05:41

    Something like this will do:

    struct debug {
        debug() {
        }
    
        ~debug() {
            std::cerr << m_SS.str() << std::endl;
        }
    
    public:
        // accepts just about anything
        template
        debug &operator<<(const T &x) {
            m_SS << x;
            return *this;
        }
    private:
        std::ostringstream m_SS;
    };
    

    Which should let you do things like this:

    debug() << "hello world";
    

    I've used a pattern like this combined with a lock to provide a stream like logging system which can guarantee that log entries are written atomically.

    NOTE: untested code, but should work :-)

提交回复
热议问题