C ++流作为成员变量

编程入门 行业动态 更新时间:2024-10-23 04:35:16
本文介绍了C ++流作为成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个C ++类,我想要保存用于日志记录的流。

I've got a C++ class which I would like to hold a stream used for logging.

流应该能够被设置

应该可以将流设置为 std :: cout 作为一个文件流记录到一个文件,或者作为一个字符串流,只是忽略数据(一个 / dev / null 排序)。在任何情况下,它应该是一个 ostream 类型对象,对象的创建者可以随时重置。

It should be possible to set the stream as std::cout, or as a file stream to log to a file, or as a stringstream which does nothing more than ignore the data (a /dev/null of sorts). In any case, it should be an ostream type object, which the creator of the object can reset at any time. The class itself is oblivious to the concrete stream type.

我可以通过指向ostream的指针来实现这一点,但是语法变得有点烦人,不得不使用deref运算符:

I could accomplish this with a pointer to an ostream, but then the syntax becomes a little annoying, having to use the deref operator:

(*m_log) << "message";

而不是

m_log << "message";

但是我不能使用引用,因为流对象需要在对象已经初始化。

But I can't use references, as the stream object needs to be possibly reset after the object has been initialized.

有没有一种优雅的方式来实现这一点,即避免使用指针,但仍然能够在构建之后重置?

Is there an elegant way to achieve this, i.e., avoid using pointers, but still be able to reset after construction?

推荐答案

您可以重置信息流:查看它 https:// ideone / Ci4eo

You can reset streams: see it live on ideone/Ci4eo

#include <fstream> #include <iostream> #include <string> struct Logger { Logger(std::ostream& os) : m_log(os.rdbuf()) { } std::streambuf* reset(std::ostream& os) { return m_log.rdbuf(os.rdbuf()); } template <typename T> friend Logger& operator<<(Logger& os, const T& t) { os.m_log << t; return os; } friend Logger& operator<<(Logger& os, std::ostream& ( *pf )(std::ostream&)) { os.m_log << pf; return os; } private: std::ostream m_log; }; int main(int argc, const char *argv[]) { Logger logto(std::cout); logto << "Hello world" << std::endl; logto.reset(std::cerr); logto << "Error world" << std::endl; return 0; }

更多推荐

C ++流作为成员变量

本文发布于:2023-07-29 08:48:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1239213.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   成员

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!