How to use my logging class like a std C++ stream?

前端 未结 5 1870
借酒劲吻你
借酒劲吻你 2020-12-24 15:34

I\'ve a working logger class, which outputs some text into a richtextbox (Win32, C++). Problem is, i always end up using it like this:

stringstream ss;  
ss          


        
5条回答
  •  [愿得一人]
    2020-12-24 16:16

    An elegant solution that also solves the flushing issues is the following:

    #include 
    #include 
    #include 
    #include 
    
    class Logger
    {
        using Stream = std::ostringstream;
        using Buffer_p = std::unique_ptr>;
    
    public:
        void log(const std::string& cmd) {
            std::cout << "INFO: " << cmd << std::endl;
        }
    
        Buffer_p log() {
            return Buffer_p(new Stream, [&](Stream* st) {
                log(st->str());
            });
        }
    };
    
    #define LOG(instance) *(instance.log())
    
    int main()
    {
        Logger logger;
        LOG(logger) << "e.g. Log a number: " << 3;
        return 0;
    }
    

提交回复
热议问题