Skip to content

Instantly share code, notes, and snippets.

@tomwhoiscontrary
Last active January 16, 2023 19:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomwhoiscontrary/93f282935a9eb9140d44c03c5bff2e62 to your computer and use it in GitHub Desktop.
Save tomwhoiscontrary/93f282935a9eb9140d44c03c5bff2e62 to your computer and use it in GitHub Desktop.
Class to save and restore ostream state in C++, to make floating point format management a bit saner
class ostream_state {
std::ostream::fmtflags flags;
std::streamsize precision = 6;
public:
class Save {
friend ostream_state;
friend std::ostream& operator<<(std::ostream& out, const Save& save) {
save.save(out);
return out;
}
ostream_state& state;
Save(ostream_state& state) : state(state) {}
void save(const std::ostream& out) const {
state.flags = out.flags();
state.precision = out.precision();
}
};
Save save() { return Save(*this); }
class Restore {
friend ostream_state;
friend std::ostream& operator<<(std::ostream& out, const Restore& restore) {
restore.restore(out);
return out;
}
const ostream_state& state;
Restore(const ostream_state& state) : state(state) {}
void restore(std::ostream& out) const {
out.flags(state.flags);
out.precision(state.precision);
}
};
Restore restore() { return Restore(*this); }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment