向 ostream 输出添加前缀
我正在寻找一种向 ostream 添加前缀的方法,将其传递给其他函数,以便它们的输出带有前缀,然后删除它以继续。
检查以下伪代码:
...
void function(ostream &out){
out << "output 1\n";
out << "output 2\n";
}
cout << "Whatever\n";
add_suffix(cout,"function: ");
function(cout);
remove_suffix(cout);
...
输出如下:
...
Whatever
function: output 1
function: output 2
...
查看 ostream 的文档,他们指出哨兵可能用于前缀/后缀,但如果预期用途是我想要的,我不知道如何执行此操作。
ostream::sentry
文档说:
sentry: Perform exception safe prefix/suffix operations
I am looking for a way of adding a prefix to an ostream, pass it down to other functions so that their outputs are prefixed and then remove it to continue.
Check the following pseudocode:
...
void function(ostream &out){
out << "output 1\n";
out << "output 2\n";
}
cout << "Whatever\n";
add_suffix(cout,"function: ");
function(cout);
remove_suffix(cout);
...
With an output like:
...
Whatever
function: output 1
function: output 2
...
Looking at the docs of ostream they state that sentry might be used for prefixing/suffixing but i don't know how to do this if the intended use is what I want.
The ostream::sentry
documentation says:
sentry: Perform exception safe prefix/suffix operations
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般的方式是这样的:定义
YourStreamBuffer
,它是一个streambuf
,它在写入的任何换行符之后插入前缀,并将输出发送到目标缓冲区。然后像这样使用它:您可以在网上找到很多关于如何实现流缓冲区的示例。
还要确保您的代码是异常安全的,即即使抛出异常也恢复 oldBuf。
注意:哨兵是不同的东西,它不是你在这里需要的。
The general way goes like this: Define
YourStreamBuffer
that is astreambuf
that inserts your prefix after any newline that is written to it, and sends the output to a destination buffer. Then use it like this:You can find plenty examples on the net on how to implement your stream buffers.
Also make sure that your code is exception safe, that is restore oldBuf even if an exception is thrown.
Note: sentries are something different, it's not what you need here.
或者,你可以为此使用一个邪恶的宏..
(是的,
__FUNCTION__
并没有在任何地方定义,但是嘿......)消极的是你必须使用宏来换行,积极的是它只为所有链接的流操作插入一次名称(在流缓冲区的情况下,它将为所有新行都有一个前缀[当然,除非这就是您想要的!])Alternatively, you could use an evil macro for this..
(yes,
__FUNCTION__
isn't defined everywhere, but hey...) Negtive is that you have to use the macro to wrap, positive is that it only inserts the name once for all chained stream operations (in the stream buffer case, it'll have a prefix for all new lines [unless that's what you want of course!])