Last active
January 16, 2023 19:42
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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