Skip to content

Commit

Permalink
fix: make std::bitset formattable again
Browse files Browse the repository at this point in the history
It used to be formattable via operator<<(ostream&) implicitly. Make it
formattable again, but this time via formatter specialization.
  • Loading branch information
muggenhor committed Sep 29, 2023
1 parent 7529af8 commit 4c3bd85
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
20 changes: 20 additions & 0 deletions include/fmt/std.h
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,26 @@ FMT_END_NAMESPACE
#endif

FMT_BEGIN_NAMESPACE
FMT_EXPORT
template <std::size_t N, typename Char> struct formatter<std::bitset<N>, Char> {
template <typename ParseContext>
FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
return ctx.begin();
}

template <typename FormatContext>
auto format(const std::bitset<N>& bs, FormatContext& ctx) const
-> decltype(ctx.out()) {
auto out = ctx.out();

for (auto pos = N; pos; --pos) {
out = detail::write<Char>(out, bs[pos - 1] ? Char('1') : Char('0'));
}

return out;
}
};

FMT_EXPORT
template <typename Char>
struct formatter<std::thread::id, Char> : basic_ostream_formatter<Char> {};
Expand Down
5 changes: 5 additions & 0 deletions test/std-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,11 @@ TEST(std_test, format_const_bit_reference) {
EXPECT_EQ(fmt::format("{} {}", v[0], v[1]), "true false");
}

TEST(std_test, format_bitset) {
const std::bitset<6> bs(42);
EXPECT_EQ(fmt::format("{}", bs), "101010");
}

TEST(std_test, format_atomic) {
std::atomic<bool> b(false);
EXPECT_EQ(fmt::format("{}", b), "false");
Expand Down

0 comments on commit 4c3bd85

Please sign in to comment.