[英]Derive from ostream or ostream_iterator to make a stream pretty printer in C++?
I have code which dumps a representation of complex objects to a stream. 我有将复杂对象的表示转储到流中的代码。 The representation uses open and close curly brackets to denote the start and end of nested objects.
该表示形式使用大括号和大括号来表示嵌套对象的开始和结束。 Rather than pretty print the representation format, I feel it's better to leave all whitespace out of the raw output and implement pretty printing, if desired, as a decorator pattern.
我认为最好将所有空白留在原始输出之外,并且如果需要,可以将漂亮的打印作为装饰图案,而不是漂亮地打印表示形式的格式。
The pretty print algorithm is simply: examine next char to output, if it is a close brace, output newline + close brace + newline. 漂亮的打印算法很简单:检查要输出的下一个字符,如果它是一个大括号,则输出换行+大括号+换行。 Else just output the char.
否则仅输出字符。
I could implement this decorator as a class derived from ostream_iterator or as a class derived from ostream. 我可以将此装饰器实现为从ostream_iterator派生的类或从ostream派生的类。 Which is more commonly done?
哪个更常用? Are there any downsides to creating an ostream wrapper?
创建ostream包装器有什么弊端吗?
The only reason where it is advisable to derive from std::ostream
is when using the derived class to construct an std::streambuf
and initialize the the base std::ostream
with it. 建议从
std::ostream
派生的唯一原因是在使用派生类构造std::streambuf
并使用其初始化基本std::ostream
时。 I don't think there is ever a reason to derive from std::ostream_iterator<...>
at all. 我认为根本没有理由从
std::ostream_iterator<...>
派生任何东西。
Instead you'd derive from std::streambuf
and override overflow()
to do whatever filter operation you want to do. 取而代之的是,您将从
std::streambuf
派生并重写overflow()
以执行所需的任何过滤器操作。 For convenience you might then derive from std::ostream
to construct a convenience stream. 为了方便起见,您可以从
std::ostream
派生出构造便利流。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.