c++ - std::ostringstream 作为函数参数的问题

标签 c++ visual-c++ stringstream

所以我今天卡在了一个简单的打印函数上,我真的不知道如何解决这个问题。基本上我想将我的字符串传递给 std::cout 风格的函数,如下所示:

foo(std::ostringstream() << "Hello" << " World!");

从我读过的内容来看,应该可以通过一个函数来实现

void foo(std::ostringstream& in)

但是在实现时我得到了一些奇怪的行为:

#include <iostream>
#include <sstream>

void foo(std::ostringstream& in)
{
    std::cout << in.str();
}

int main()
{
    std::ostringstream working;
    working << "Hello" << " World!";
    foo(working);                   // OK
    std::ostringstream notWorking;
    notWorking << "Hello";
    foo(notWorking<<" World!");     // Not OK?!
    return 0;
}

虽然 foo 的第一个调用看起来不错并且按预期工作,但第二个调用拒绝编译,即使它们(从我的角度来看)在技术上应该是同一件事。

错误:

error C2664: 'void foo(std::ostringstream &)': cannot convert parameter 1 from 'std::basic_ostream<char,std::char_traits<char>>' to 'std::ostringstream &'

我在 Win7 x64 上使用 MS Visual Studio 2013 Express

最佳答案

IO 操作的移位运算符的重载通过引用获取基本流。即:

std::ostream& operator<<( std::ostream& os , foo myfo )
{
    os << myfoo;

    return os;
}

所以使用 std::ostream 而不是 std::ostringstream 作为函数参数:

void f( std::ostream& stream );

关于c++ - std::ostringstream 作为函数参数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24315434/

相关文章:

c++ - 未解析为候选容器的模板运算符模板

c++ - 将指针更改为指向指针的引用

c# - 如何将 C++ 对象传递给 C# 类库

c++ - C/C++ 编译器如何为某些 C 函数调用自动推断数组长度?

visual-c++ - 安装 Visual Studio 2019 后缺少 vcvarsall.bat

C++ getline() 跳过空字符串

c++ - 使用 stringstream 对字符串进行标记,其中最后一个字符是分隔符

C++构造函数差异

c++ - std::stringstream 类需要有 dll 接口(interface)

c++ - swift 4 : Pass multidimensional array to c++