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

前端 未结 5 1873
借酒劲吻你
借酒劲吻你 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 15:57

    As Luc Hermitte noted, there is "Logging In C++" article which describes very neat approach to solve this problem. In a nutshell, given you have a function like the following:

    void LogFunction(const std::string& str) {
        // write to socket, file, console, e.t.c
        std::cout << str << std::endl;
    }
    

    it is possible to write a wrapper to use it in std::cout like way:

    #include 
    #include 
    
    #define LOG(loggingFuntion) \
        Log(loggingFuntion).GetStream()
    
    class Log {
        using LogFunctionType = std::function;
    
    public:
        explicit Log(LogFunctionType logFunction) : m_logFunction(std::move(logFunction)) { }
        std::ostringstream& GetStream() { return m_stringStream; }
        ~Log() { m_logFunction(m_stringStream.str()); }
    
    private:
        std::ostringstream m_stringStream;
        LogFunctionType m_logFunction;
    };
    
    int main() {
        LOG(LogFunction) << "some string " << 5 << " smth";
    }
    

    (online demo)

    Also, there is very nice solution provided by Stewart.

提交回复
热议问题