Applying ANSI styles/colors to a value in a scope.
The ScopedAnsiWrapper
class applies an ANSI "on" code before the value and an "off" code immediately after. This makes styles and colors scoped to the wrapped value, unlike persistent toggles.
Example:
std::cout << comppare::internal::ansi::BOLD("Bold Text")
<< " normal text";
The text "Bold Text"
is printed in bold, and the style is automatically reset afterwards.
- Template Parameters
-
T | The type of the value to be wrapped. Must satisfy Streamable (i.e. it can be inserted into a std::ostream ). |
Implementation Details
Private Data Members:
on_
– ANSI code to enable the style/color
off_
– ANSI code to disable it
val_
– the wrapped value operator<<
:
- Saves the current formatting state of the stream with copyfmt
- Streams the value
val_
into a temporary std::ostringstream
- Writes
on_ + value + off_
to the original stream.
- Restores the saved formatting state so it does not affect formatting.
Friend operator<<
The insertion operator is declared as a friend
so it can access the wrapper’s private members on_, off_, and val_.:
Applying ANSI styles/colors to a value in a scope.
Definition ansi.hpp:130
friend std::ostream & operator<<(std::ostream &os, ScopedAnsiWrapper const &w)
Overloaded operator<< to stream the value with ANSI codes.
Definition ansi.hpp:149
This allows syntax like:
std::cout << RED("Red") << " Normal";