我正在为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
,只是经过了运算符并返回了以前的值。
谢谢!
答案 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&) );