Skip to content

Instantly share code, notes, and snippets.

@orlp
Created October 30, 2014 22:43
Show Gist options
  • Save orlp/e6df03fcbcc9976062bc to your computer and use it in GitHub Desktop.
Save orlp/e6df03fcbcc9976062bc to your computer and use it in GitHub Desktop.
// Used to save, modify and restore stream state formatting parameters.
template<class Char, class Trait>
struct stream_state {
using fmtflags = std::ios_base::fmtflags;
std::streamsize width;
std::streamsize precision;
Char fill;
fmtflags flags;
stream_state(const std::basic_ostream<Char, Trait>& s)
: width(s.width()), precision(s.precision()), fill(s.fill()), flags(s.flags()) { }
static stream_state default_for_stream(const std::basic_ostream<Char, Trait>& s) {
stream_state default_state;
default_state.width = 0;
default_state.precision = 6;
default_state.fill = s.widen(' ');
default_state.flags = s.dec | s.skipws;
return default_state;
}
fmtflags setf(fmtflags new_flags) {
auto old = flags;
flags |= new_flags;
return old;
}
fmtflags setf(fmtflags new_flags, fmtflags mask) {
auto old = flags;
flags = (flags & ~mask) | (new_flags & mask);
return old;
}
void apply(std::basic_ostream<Char, Trait>& s) {
s.width(width);
s.precision(precision);
s.fill(fill);
s.flags(flags);
}
private:
stream_state() = default;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment