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

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

本文关键字:std ostream lt 为什么 重载 什么 时的      更新时间:2023-10-16

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

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

在这种情况下,我理解(或者可能不理解?)我正在使用std::ostream& (*f)(std::ios &)重载运算符<<以进行MyCout,但这是为什么呢?f(std::cout)实际上做了什么,为什么我需要用这个函数重载运算符?似乎根本没有使用s,只是通过操作员并返回与以前相同的内容。

谢谢!

std::ostream& (*f)(std::ios &)是一个名为 f 的函数指针,它指向将std::ios &作为其唯一参数并返回std::ostream&的函数。 对于某些流操纵器(如 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&) );