Overload handling of std::endl?

后端 未结 7 970
广开言路
广开言路 2020-11-27 04:40

I want to define a class MyStream so that:

MyStream myStream;
myStream << 1 << 2 << 3 << std::endl << 5 << 6         


        
相关标签:
7条回答
  • 2020-11-27 05:16

    I had the same question, and I thought that Potatoswatter's second answer had merit: "Just declare a new endl in your own namespace, or better, a manipulator which isn't called endl at all!"

    So I found out how to write a custom manipulator which is not hard at all:

    #include <sstream>
    #include <iostream>
    
    class log_t : public std::ostringstream
    {
        public:
    };
    
    
    std::ostream& custom_endl(std::ostream& out)
    {
        log_t *log = dynamic_cast<log_t*>(&out);
        if (log)
        {
            std::cout << "custom endl succeeded.\n";
        }
        out << std::endl;
        return out;
    }
    
    std::ostream& custom_flush(std::ostream& out)
    {
        log_t *log = dynamic_cast<log_t*>(&out);
        if (log)
        {
            std::cout << "custom flush succeeded.\n";
        }
        out << std::flush;
        return out;
    }
    
    int main(int argc, char **argv)
    {
        log_t log;
    
        log << "custom endl test" << custom_endl;
        log << "custom flush test" << custom_flush;
    
        std::cout << "Contents of log:\n" << log.str() << std::endl;
    }
    

    Here's the output:

    custom endl succeeded.
    custom flush succeeded.
    Contents of log:
    custom endl test
    custom flush test
    

    Here I've created two custom manipulators, one that handles endl and one that handles flush. You can add whatever processing you want to these two functions, since you have a pointer to the log_t object.

    0 讨论(0)
提交回复
热议问题