customize cout

前端 未结 6 964
你的背包
你的背包 2021-02-06 00:22

How can I derive a class from cout so that, for example, writing to it

new_cout << \"message\";

would be equivalent to

6条回答
  •  -上瘾入骨i
    2021-02-06 00:51

    class Log
    {
    public:
        Log(const std::string &funcName)
        {
            std::cout << funcName << ": ";
        }
    
        template 
        Log &operator<<(const T &v)
        {
            std::cout << v;
            return *this;
        }
    
        ~Log()
        {
            std::cout << " [end of message]" << std::endl;
        }
    };
    
    #define MAGIC_LOG Log(__FUNCTION__)
    

    Hence:

    MAGIC_LOG << "here's a message";
    MAGIC_LOG << "here's one with a number: " << 5;
    

提交回复
热议问题