How do the stream manipulators work?

前端 未结 3 1847
予麋鹿
予麋鹿 2020-11-29 05:17

It is well known that the user can define stream manipulators like this:

ostream& tab(ostream & output)
{
    return output<< \'\\t\';
} 
         


        
3条回答
  •  清歌不尽
    2020-11-29 05:57

    The standard defines the following operator<< overload in the basic_ostream class template:

    basic_ostream& operator<<(
        basic_ostream& (*pf) (basic_ostream&) );
    

    Effects: None. Does not behave as a formatted output function (as described in 27.6.2.5.1).

    Returns: pf(*this).

    The parameter is a pointer to a function taking and returning a reference to a std::ostream.

    This means that you can "stream" a function with this signature to an ostream object and it has the effect of calling that function on the stream. If you use the name of a function in an expression then it is (usually) converted to a pointer to that function.

    std::hex is an std::ios_base manipulator defined as follows.

       ios_base& hex(ios_base& str);
    

    Effects: Calls str.setf(ios_base::hex, ios_base::basefield).

    Returns: str.

    This means that streaming hex to an ostream will set the output base formatting flags to output numbers in hexadecimal. The manipulator doesn't output anything itself.

提交回复
热议问题