How to create functions like std::cout?

后端 未结 6 607
盖世英雄少女心
盖世英雄少女心 2021-01-03 16:40

I\'m creating my own logging utility for my project, I want to create a function like iostream\'s std::cout, to log to a file and print to the console as well.

Here\

6条回答
  •  心在旅途
    2021-01-03 16:51

    The trick is for your LOG(level) to return a special type which contains a pointer to an std::ostream, and defines the << operator. Something like:

    class LogStream
    {
        std::ostream* myDest;
    public:
        LogStream( std::ostream* dest ) : myDest( dest ) {}
    
        template 
        LogStream& operator<<( T const& obj )
        {
            if ( myDest != nullptr ) {
                *myDest << obj;
            }
            return *this;
        }
    };
    

    The LOG(level) macro creats an instance of one, something like:

    #define LOG(level) LogStream( getLogStream( level, __FILE__, __LINE__ ) )
    

    Of course, the getLogStream may insert any information it wants (like a timestamp) at the moment it is called.

    You might want to add a flush in the destructor of LogStream.

提交回复
热议问题