【问题标题】:What is `std::ostream& (*f)(std::ostream &)` when overloading `<<` and why I would need it?重载`<<`时什么是`std::ostream& (*f)(std::ostream &)`,为什么我需要它?
【发布时间】:2019-01-08 18:43:49
【问题描述】:

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

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

在这种情况下,我了解(或者可能不是?)我正在使用 std::ostream&amp; (*f)(std::ios &amp;)MyCout 重载运算符 &lt;&lt;,但这是为什么呢? f(std::cout) 实际上做了什么,为什么我需要用这个函数重载运算符?貌似s根本没有使用,只是通过操作符,返回和之前一样。

谢谢!

【问题讨论】:

    标签: c++ stream operator-overloading


    【解决方案1】:

    std::ostream&amp; (*f)(std::ios &amp;) 是一个名为f 的函数指针,它指向以std::ios &amp; 作为其唯一参数并返回std::ostream&amp; 的函数。这是一些stream manipulators 需要的,比如std::endl,它是一个函数,而不是像std::cout 这样的对象。

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


    不要以为这个函数签名不是你真正想要的。输入参数类型和返回类型应该相同。采用操纵器功能的operator &lt;&lt; 的标准重载是

    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&) );
    

    【讨论】:

    • 我会质疑将std::ios 作为参数并返回std::ostream 的奇怪用法。通常返回类型和参数必须匹配才能直观地工作,使它们不同没有什么意义。
    • 谢谢! std::cout 是一个函数的知识刚刚从我的脑海中消失。
    • @Eric std::cout 是一个对象(std::ostream 类的一个实例)。 std::ostream 类重载了&lt;&lt; 运算符,以便std::endl(一个函数)可以出现在运算符的右侧(即std::cout &lt;&lt; "hello" &lt;&lt; std::endl)。
    • @0x499602D2 哦,当然!我的意思是endl,当时我脑子里想的太多了。我需要休息一下哈哈
    猜你喜欢
    • 1970-01-01
    • 2014-01-13
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    • 2019-08-22
    相关资源
    最近更新 更多