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

前端 未结 5 1893
借酒劲吻你
借酒劲吻你 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:02

    You need to implement operator << appropriately for your class. The general pattern looks like this:

    template 
    logger& operator <<(logger& log, T const& value) {
        log.your_stringstream << value;
        return log;
    }
    

    Notice that this deals with (non-const) references since the operation modifies your logger. Also notice that you need to return the log parameter in order for chaining to work:

    log << 1 << 2 << endl;
    // is the same as:
    ((log << 1) << 2) << endl;
    

    If the innermost operation didn't return the current log instance, all other operations would either fail at compile-time (wrong method signature) or would be swallowed at run-time.

提交回复
热议问题