“回滚”或撤消任何应用于流的操纵器,而无需知道操纵器是什么 [英] "Roll-Back" or Undo Any Manipulators Applied To A Stream Without Knowing What The Manipulators Were
问题描述
如果我对流应用任意数量的操纵器,是否有办法以通用方式撤消那些操纵器的应用?
If I apply an arbitrary number of manipulators to a stream, is there a way to undo the application of those manipulators in a generic way?
例如,考虑以下内容:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << "Hello" << hex << 42 << "\n";
// now i want to "roll-back" cout to whatever state it was in
// before the code above, *without* having to know
// what modifiers I added to it
// ... MAGIC HAPPENS! ...
cout << "This should not be in hex: " << 42 << "\n";
}
假设我想在 MAGIC HAPPENS
会将流操纵器的状态恢复到我做 cout<<之前的状态。十六进制
。 但是我不知道我添加了哪些操纵器。我怎么能做到这一点?
Suppose I want to add code at MAGIC HAPPENS
that will revert the state of the stream manipulators to whatever it was before I did cout << hex
. But I don't know what manipulators I added. How can I accomplish this?
换句话说,我希望能够写出这样的东西(伪代码/幻想代码):
In other words, I'd like to be able to write something like this (psudocode/fantasy code):
std::something old_state = cout.current_manip_state();
cout << hex;
cout.restore_manip_state(old_state);
这可能吗?
如果您很好奇,我有兴趣在自定义的 operator<<()
我正在写一个复杂的类型。该类型是一种有区别的联合,并且不同的值类型将对流应用不同的操作。
In case you're curious, I'm interested in doing this in a custom operator<<()
I'm writing for a complex type. The type is a kind of discriminated union, and different value types will have different manips applied to the stream.
限制:我不能使用Boost或任何其他第三方库。解决方案必须使用标准C ++。
Restriction: I cannot use Boost or any other 3rd party libraries. Solution must be in standard C++.
推荐答案
是。
您可以保存状态并恢复状态:
You can save the state and restore it:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
std::ios state(NULL);
state.copyfmt(std::cout);
cout << "Hello" << hex << 42 << "\n";
// now i want to "roll-back" cout to whatever state it was in
// before the code above, *without* having to know what modifiers I added to it
// ... MAGIC HAPPENS! ...
std::cout.copyfmt(state);
cout << "This should not be in hex: " << 42 << "\n";
}
如果您想返回默认状态,则甚至不需要要保存状态,可以从临时对象中提取状态。
If you want to get back to the default state you don't even need to save the state you can extract it from a temporary object.
std::cout.copyfmt(std::ios(NULL));
这篇关于“回滚”或撤消任何应用于流的操纵器,而无需知道操纵器是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!