C++ logging using ostream

前端 未结 3 1671
鱼传尺愫
鱼传尺愫 2021-01-17 04:02

I\'m making a logger. I want to create a function log() that takes a stream as input.

For instance:

log(\"hello\"<<\" \"<<\"         


        
3条回答
  •  再見小時候
    2021-01-17 05:04

    You can't create a function like the one you want. You can, however, create a macro that handles that stuff for you:

    // "log" may be defined in the  header file
    // so undefine it if needed
    #ifdef log
    # undef log
    #endif
    #define log(stream)          \
        do {                     \
            acquire_lock();      \
            std::cout << stream; \
            release_lock();      \
        } while(0)
    

    You have to change the acquire_lock and release_lock calls to the proper ones for you. And of course use a stream that is appropriate for you as well.

提交回复
热议问题