Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add formatter for std::atomic #3574

Merged
merged 1 commit into from
Aug 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion include/fmt/std.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#ifndef FMT_STD_H_
#define FMT_STD_H_

#include <atomic>
#include <bitset>
#include <cstdlib>
#include <exception>
Expand Down Expand Up @@ -435,6 +436,17 @@ struct formatter<BitRef, Char,
}
};

FMT_END_NAMESPACE
FMT_EXPORT
template <typename T, typename Char>
struct formatter<std::atomic<T>, Char,
enable_if_t<is_formattable<T, Char>::value>>
: formatter<T, Char> {
template <typename FormatContext>
auto format(const std::atomic<T>& v, FormatContext& ctx) const
-> decltype(ctx.out()) {
return formatter<T, Char>::format(v.load(), ctx);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe its better to use load(std::memory_order_acquire) or even load(std::memory_order_relaxed)?

}
};

FMT_END_NAMESPACE
#endif // FMT_STD_H_
8 changes: 8 additions & 0 deletions test/std-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -236,3 +236,11 @@ TEST(std_test, format_const_bit_reference) {
const std::vector<bool> v = {true, false};
EXPECT_EQ(fmt::format("{} {}", v[0], v[1]), "true false");
}

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

const std::atomic<bool> cb(true);
EXPECT_EQ(fmt::format("{}", cb), "true");
}