【问题标题】:Is it possible to pass a stringstream as a function parameter?是否可以将字符串流作为函数参数传递?
【发布时间】:2012-06-05 16:27:47
【问题描述】:

是否可以传入一个字符串流并让函数直接写入它?

我记得我看到一个类似这样的函数调用:

my_func(ss << "text" << hex << 33);

【问题讨论】:

    标签: c++ function parameter-passing stringstream


    【解决方案1】:

    当然。为什么不呢?此类函数的示例声明:

    void my_func(std::ostringstream& ss);
    

    【讨论】:

    • 谢谢你,我错过了什么,我知道这是有可能的,但我不知道使用什么声明来达到那个效果
    • 除了ss &lt;&lt; "test" &lt;&lt; hex &lt;&lt; 33的类型不是std::stringstream&amp;,而是std::ostream&amp;,和给定的签名不匹配。
    【解决方案2】:

    绝对!确保通过引用而不是值传递它。

    void my_func(ostream& stream) {
        stream << "Hello!";
    }
    

    【讨论】:

    • 为什么只能通过引用传递?
    • @aderchox 否则它不会编译(流没有复制构造函数)。
    【解决方案3】:

    my_func 必须有如下签名:

    void my_func( std::ostream& s );
    

    ,因为那是ss &lt;&lt; "text" &lt;&lt; hex &lt;&lt; 33 的类型。如果目标是 要提取生成的字符串,您必须执行以下操作:

    void
    my_func( std::ostream& s )
    {
        std::string data = dynamic_cast<std::ostringstream&>(s).str();
        //  ...
    }
    

    还要注意,您不能使用临时流;

    my_func( std::ostringstream() << "text" << hex << 33 );
    

    不会编译(可能使用 VC++ 除外),因为它不是合法的 C++。你 可以这样写:

    my_func( std::ostringstream().flush() << "text" << hex << 33 );
    

    如果你想使用临时的。但这对用户不太友好。

    【讨论】:

      【解决方案4】:

      是的,而且

      Function(expresion)
      

      将首先计算表达式并将其结果作为参数传递

      注意:Operator << for ostreams 返回一个 ostream

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多