什么是重载`<<`时`std :: ostream&(* f)(std :: ostream&)`,为什么我需要它?

时间:2019-01-08 18:43:50

标签: c++ stream operator-overloading

我正在为boost.log包装器工作,发现this的问题似乎是我想要的,但不是std::cout与我还不了解的boost流有关。为此,我一直想知道为什么需要它以及它实际上在做什么。例如:

MyCout& operator<< (MyCout &s, std::ostream& (*f)(std::ios &)) {
    f(std::cout);
    return s;
}

在这种情况下,我了解(或可能不是?)我正在使用<<重载MyCout的运算符std::ostream& (*f)(std::ios &),但这是为什么呢? f(std::cout)的实际作用是什么,为什么我需要使用此函数来重载运算符?似乎根本没有使用s,只是经过了运算符并返回了以前的值。

谢谢!

1 个答案:

答案 0 :(得分:4)

std::ostream& (*f)(std::ios &)是一个名为f的函数指针,它指向将std::ios &作为其唯一参数并返回std::ostream&的函数。对于像stream manipulators这样的某些std::endl来说,这是一个函数,而不是像std::cout这样的对象。

通过这种重载,您可以将函数流式传输到流中,并让该函数对流进行某种操作


请不要使此函数签名不是您真正想要的。输入参数类型和返回类型应该相同。具有操纵器功能的operator <<的标准重载为

basic_ostream& operator<<(
    std::ios_base& (*func)(std::ios_base&) );

basic_ostream& operator<<(
    std::basic_ios<CharT,Traits>& (*func)(std::basic_ios<CharT,Traits>&) );

basic_ostream& operator<<(
    std::basic_ostream<CharT,Traits>& (*func)(std::basic_ostream<CharT,Traits>&) );

basic_istream& operator>>( 
    std::ios_base& (*func)(std::ios_base&) );

basic_istream& operator>>( 
    std::basic_ios<CharT,Traits>& (*func)(std::basic_ios<CharT,Traits>&) );

basic_istream& operator>>( 
    basic_istream& (*func)(basic_istream&) );