将多个字符串串联尝试传递给 ostringstream 参数

Passing Multiple Strings in Concatenation Attempt to an ostringstream Parameter

我正在尝试创建一个方法来接受将被记录到文件中的流(即 ostringstream)参数。

在头文件中,声明为:

static void Log(const std::ostringstream& message, LoggingSeverity severity = LoggingSeverity::info);

但是,当我尝试从另一个 class 调用该方法时,例如:

SimpleLogger::Log("Name registered.", SimpleLogger::LoggingSeverity::trace);

我收到以下错误:E0415 no suitable constructor exists to convert from "const char []" to "std::basic_ostringstream<char, std::char_traits<char>, std::allocator<char>>"

如果我尝试通过连接字符串(input 属于 std::string 类型)来构建调用,如下所示:

SimpleLogger::Log("String to int conversion of [" << input << "] failed.", SimpleLogger::LoggingSeverity::warning);

我收到以下错误:E0349 no operator "<<" matches these operands

从错误中,我了解到 std::ostringstream 参数不喜欢字符串,但我的印象是数据类型会为我提供能够向流,包括例如 int 值。是否有更好的数据类型来达到预期的效果?或者,对方法的结构化调用是否不正确?

这里的问题是您将字符串传递给 stringstram 构造函数,这个想法没问题,但是构造函数是显式定义的,因此没有从字符串到字符串流的自动转换,explicit stringstream (const string& str , ios_base::openmode which = ios_base::in | ios_base::out);,您可以查找详细信息 here

关于你的问题,这里有一个示例代码,

#include <string>
#include <iostream>
#include <sstream>

void Logg(const std::ostringstream& message) {
    std::cout<<message.str()<<std::endl;
}

int main()
{
    std::string a= "other message";
    Logg(std::ostringstream("some message"));
    Logg(std::ostringstream(a));
    Logg(static_cast<std::ostringstream>(a));
}

输出

some message
other message
other message