0

我有一个包含 QTextStream 的简单容器类。我用它来写入文件。我想要的是下面的函数在流运算符调用“ LogHandle() << "foo" << 1234;”的开头添加一个前缀。例如"LOG:",最后换行endl。简单地在操作员的每次呼叫中添加这样的东西<<当然是行不通的。

预期输出:

Log: foo 1234 *break*

当前代码:

class Handle{
public:
    Handle() {
        QString path = QCoreApplication::applicationDirPath();
        path.append("/foo.log");
        _file.setFileName(path);
        _stream.setDevice(&_file);
    }

    QFile _file;
    QTextStream _stream;
};

template <class T>
Handle& operator<< (Handle& out, T msg) {
    out._file.open(QIODevice::WriteOnly | QIODevice::Append);
    out._stream << msg;
    return out;
}
4

0 回答 0