Overload handling of std::endl?

后端 未结 7 996
广开言路
广开言路 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 04:59

    Your overloaded operators of the MyStream class have to set a previous-printed-token-was-endl flag.

    Then, if the next object is printed, the [blah] can be inserted in front of it.

    std::endl is a function taking and returning a reference to std::ostream. To detect it was shifted into your stream, you have to overload the operator<< between your type and such a function:

    MyStream& operator<<( std::ostream&(*f)(std::ostream&) )
    {
        std::cout << f;
    
        if( f == std::endl )
        {
            _lastTokenWasEndl = true;
        }
    
        return *this;
    }
    

提交回复
热议问题