为简单起见,使用来自静态成员函数的 std::stringstream

Using a std::stringstream from static member function for simplicity

本文关键字:函数 静态成员 std stringstream 简单      更新时间:2023-10-16

我需要一个接口来将短消息写入日志文件,消息通常包含多个部分,例如标识符和值。

为了做到这一点,我创建了一个处理很多小东西的类,例如创建带有时间戳的文件名等,尽管我不想使用变量参数列表(int nargs, ...),所以我认为我最好的选择是将std::stringstream传递给 write 函数。

我希望能够将这些调用编写为单行,而不必每次需要执行此操作时都创建std::stringstream,因此我创建了一个静态成员函数来返回一个字符串流对象,我可以与我的写入函数一起使用,尽管由于某种原因它不起作用。

MyClass.h

class MyClass {
public:
    static std::stringstream& stream();
    void write(std::ostream& datastream);
private:
    static std::stringstream* _stringstream;
};

我的班级.cpp

std::stringstream* MyClass::_stringstream = new std::stringstream();
std::stringstream& MyClass::stream() {
    MyClass::_stringstream->str(std::string());
    return *MyClass::_stringstream;
}
void MyClass::write(std::string data) {
    this->_fhandle << data << std::endl;
}
void MyClass::write(std::ostream& datastream) {
    std::string data = dynamic_cast<std::ostringstream&>(datastream).str();
    this->write(data);
}

主.cpp

MyClass* info = new MyClass();
info->write("Hello, world");
info->write(MyClass::stream() << "Lorem" << ", " << "ipsum");
info->write(MyClass::stream() << "dolor sit" << " amet");

代码可以编译,但是在执行应用程序时,我得到了一个std::bad_cast异常...

那是因为你正在创建一个std::stringstream,它不是从std::ostringstream派生的。 只需创建一个 std::ostringstreambad_cast应该消失。

话虽如此,多次重复使用std::ostringstream像这样通常不是一个好主意;iostream 类是充满状态,每次使用之间不会重置。 它最好每次都创建新实例。 (古典这种事情的解决方案是创建一个可复制的包装器类,转发到std::ostream。 这个的一个例子由 info->write() 返回,因此可以写info->write() << "Hello, world" ...