From 1e43758b5435bcf54ad82e39cff6c89bcd9b5fb4 Mon Sep 17 00:00:00 2001 From: Mateusz Pusz Date: Tue, 23 Jan 2024 21:19:45 +0100 Subject: [PATCH] feat: unit text output support added Resolves #422 --- src/core/include/mp-units/ostream.h | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/core/include/mp-units/ostream.h b/src/core/include/mp-units/ostream.h index 248b05af..3f462fb1 100644 --- a/src/core/include/mp-units/ostream.h +++ b/src/core/include/mp-units/ostream.h @@ -31,6 +31,12 @@ namespace mp_units { namespace detail { +template +void to_stream(std::basic_ostream& os, U u) +{ + unit_symbol_to(std::ostream_iterator(os), u); +} + template void to_stream(std::basic_ostream& os, const quantity& q) { @@ -40,11 +46,28 @@ void to_stream(std::basic_ostream& os, const quantity& q) else os << q.numerical_value_ref_in(q.unit); if constexpr (space_before_unit_symbol) os << " "; - unit_symbol_to(std::ostream_iterator(os), get_unit(R)); + to_stream(os, get_unit(R)); } } // namespace detail +template +std::basic_ostream& operator<<(std::basic_ostream& os, U u) +{ + if (os.width()) { + // std::setw() applies to the whole uni output so it has to be first put into std::string + std::basic_ostringstream oss; + oss.flags(os.flags()); + oss.imbue(os.getloc()); + oss.precision(os.precision()); + detail::to_stream(oss, u); + return os << std::move(oss).str(); + } + + detail::to_stream(os, u); + return os; +} + template std::basic_ostream& operator<<(std::basic_ostream& os, const quantity& q) requires requires { os << q.numerical_value_ref_in(q.unit); }