How to create functions like std::cout?

后端 未结 6 639
盖世英雄少女心
盖世英雄少女心 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 17:10

    std::cout is not a function, it's an object of type std::ostream which overloads operator<<.

    A quick sketch of how you could do it:

    enum Level {
        debug, error, warning, info
    };
    
    struct Logger {
        std::ostream* stream;  // set this in a constructor to point
                               // either to a file or console stream
        Level debug_level;
    public:
        Logger& operator<<(const std::string& msg)
        {
            *stream << msg; // also print the level etc.
            return *this;
        }
    
        friend Logger& log(Logger& logger, Level n);
        {
            logger.debug_level = n;
            return logger;
        }
    };
    

    Ant then use it like

    Logger l;
    log(l, debug) << "test";
    

提交回复
热议问题