【问题标题】:How can I (cleanly!) subclass std::stringstream for a customization? [closed]我如何(干净地!)子类化 std::stringstream 以进行自定义? [关闭]
【发布时间】:2017-03-02 18:17:47
【问题描述】:

我有一个带有 std::stringstream 成员的日志记录类。我使用它的输出

这就是问题所在。将数据发送到流中后,我想要一种简单的方法将其自动刷新到我的目的地(本质上是可变/动态的)。

std::ostream 将“自动刷新”,如果您发送 endl 向下它。这是我会复制的可接受的解决方案。

我怎样才能自己实现呢?请注意,我不想覆盖 std::stringstream 中的每个 operator<<() 重载!

【问题讨论】:

  • "请注意,我不想覆盖 std::stringstream 中的每个 使用像 std::stringstream 这样的模板重载吗?
  • 那是怎样的一个骗局?
  • @Captain 这有点牵强。
  • 您将stringstream 定义为成员并定义您自己的operator <<(T &&t) 将forwards 发送给stringstream 然后flushes 怎么样?
  • 请发布您的代码

标签: c++ string stream


【解决方案1】:

我做过类似的事情。我所做的是使用一个未命名的类实例来消耗输出并将刷新放入析构函数中。像这样的:

int i = 0;
MyClass() << "This is a log message containing an int: " << i;
// here, the class destructs and does whatever you need to do to flush the stream

【讨论】:

  • 算子重载到底是怎么做的?
  • 嗯。这很有趣!那么我是否应该只继承 std::stringstream 并且只覆盖它的析构函数?
  • @BuvinJ 你可以。但在我的情况下,我需要类来做其他事情,所以我只是让 stringstream 成为成员。
  • @πάνταῥεῖ 我只是使用一个模板成员函数来实现 operator
  • 出色的解决方案。这可能适用于很多目的!你让我开心!
【解决方案2】:

与其继承std::stringstream,不如使用组合(参见Composition over inheritance)。

有了这个,你的类将如下所示:

class Log{

    std::stringstream _stream;

    [...] // Constructor and other class logic

    public:
    Log& operator<<(string s){
        _stream << s << endl;
        return *this;
    }

};

【讨论】:

  • 谢谢。虽然我已经将它作为成员,但我的 Log 类不是我
猜你喜欢
  • 2014-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-25
  • 1970-01-01
相关资源
最近更新 更多