简体   繁体   English

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

[英]What is `std::ostream& (*f)(std::ostream &)` when overloading `<<` and why I would need it?

I'm working in a wrapper for boost.log and found this question that seems to be what I want, but instead of std::cout would be something related to the boost stream that I don't really know yet. 我正在使用boost.log包装程序 ,发现这个问题似乎是我想要的,但不是std::cout而是与我还不真正知道的boost流相关的东西。 For that, I stuck wondering why it is needed and what it's actually doing. 为此,我一直想知道为什么需要它以及它实际上在做什么。 For example: 例如:

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

In this case I understand (or maybe not?) that I'm overloading the operator << for MyCout using the std::ostream& (*f)(std::ios &) , but why is that? 在这种情况下,我了解(或可能不了解?)我正在使用std::ostream& (*f)(std::ios &)重载MyCout的运算符<< ,但是为什么呢? What the f(std::cout) actually does and why I would need to overload the operator with this function? f(std::cout)实际作用是什么,为什么我需要用此函数重载运算符? It seems that s is not been used at all, just passing through the operator and returning the same as before. 似乎根本没有使用s ,只是通过运算符并返回与以前相同的值。

Thanks! 谢谢!

std::ostream& (*f)(std::ios &) is a function pointer named f and it points to function that takes a std::ios & as its only parameter and returns a std::ostream& . std::ostream& (*f)(std::ios &)是名为f的函数指针,它指向以std::ios &作为唯一参数并返回std::ostream&函数。 This is needed for some of the stream manipulators like std::endl , which is a function, not an object like std::cout is. 这对于某些流操纵器(std::endl是必需的,它是一个函数,而不是像std::cout这样的对象。

With this overload you can stream a function into your stream and have that function do some sort of manipulation of the stream 通过这种重载,您可以将函数流式传输到流中,并使该函数对流进行某种操作


Do not that this function signature isn't what you really want. 不要说这个函数签名不是您真正想要的。 The input parameter type and return type should be the same. 输入参数类型和返回类型应该相同。 The standard overloads for operator << that take manipulator functions are 具有操作器功能的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&) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM