我正在尝试创建一个方法,该方法将接受将记录到文件中的流(即 ostringstream)参数。
在头文件中声明为:
static void Log(const std::ostringstream& message, LoggingSeverity severity = LoggingSeverity::info);
但是,当我尝试从另一个类调用该方法时,例如:
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
值。有没有更好的数据类型来达到预期的结果?或者,对方法的结构化调用是否不正确?
答案 0 :(得分:2)
嗯,这里的问题是你将一个字符串传递给一个 stringstram 构造函数,这个想法是好的,但是构造函数是显式定义的,所以没有从字符串到 stringstream 的自动转换,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