Created
April 2, 2025 19:11
-
-
Save dbremner/1161f7ea74f1f814cc08b98cc070c552 to your computer and use it in GitHub Desktop.
guard class for ostream state flags
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
#pragma once | |
#include <ostream> | |
/// RAII guard class for saving and restoring ostream state | |
class ostream_guard final | |
{ | |
std::ostream *os_; | |
std::streamsize width_; | |
std::streamsize precision_; | |
std::ios::fmtflags flags_; // Moved here to reduce padding | |
char fill_; | |
public: | |
explicit ostream_guard(std::ostream& os) | |
: os_(&os), | |
width_(os.width()), | |
precision_(os.precision()), | |
flags_(os.flags()), | |
fill_(os.fill()) | |
{ | |
} | |
~ostream_guard() | |
{ | |
os_->flags(flags_); | |
os_->width(width_); | |
os_->precision(precision_); | |
os_->fill(fill_); | |
} | |
ostream_guard(const ostream_guard&) = delete; | |
ostream_guard& operator=(const ostream_guard&) = delete; | |
ostream_guard(ostream_guard&&) = delete; | |
ostream_guard& operator=(ostream_guard&&) = delete; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment