customize cout

前端 未结 6 1050
你的背包
你的背包 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条回答
  •  离开以前
    2021-02-06 00:57

    For logging purposes I use something like

    #define LOG(x) \
      cout << __FUNCTION__ << x << endl
    
    // ...
    LOG("My message with number " << number << " and some more");
    

    The problem with your approach is (as Mykola Golybyew explained) that FUNCTION is processed at compile time and would therefore always print the same name with a non-preprocessor solution.

    If it's only for adding endl to your messages, you could try something like:

    class MyLine {
    public:
      bool written;
      std::ostream& stream;
      MyLine(const MyLine& _line) : stream(_line.stream), written(false) { }
      MyLine(std::ostream& _stream) : stream(_stream), written(false) { }
      ~MyLine() { if (!written) stream << "End of Message" << std::endl; }
    };
    
    template  MyLine operator<<(MyLine& line, const T& _val) {
      line.stream << _val;
      line.written = true;
      return line;
    }
    
    class MyStream {
    public:
      std::ostream& parentStream;
      MyStream(std::ostream& _parentStream) : parentStream(_parentStream) { }
      MyLine getLine() { return MyLine(parentStream); }
    };
    
    template  MyLine operator<<(MyStream& stream, const T& _val) {
      return (stream.getLine() << _val);
    }
    
    int main()
    {
          MyStream stream(std::cout);
          stream << "Hello " << 13 << " some more data";
          stream << "This is in the next line " << " 1 ";
        return 0;
    }
    

    Note, that it's important not to return references from the operator functions. Since the MyLine should only exist as a temporary (for its destructor triggers the writing of the endl), the first object (returned by the getLine() function in MyStream) would be destructed before the second operator<< is called. Therefore the MyLine object is copied in each operator<< creating a new one. The last object gets destructed without being written to and writed the end of the message in its destructor.

    Just try it out in the debugger to understand whats going on...

提交回复
热议问题