Skip to content

Commit

Permalink
Add support formatting std::expected<void, E>
Browse files Browse the repository at this point in the history
Signed-off-by: Vladislav Shchapov <[email protected]>
  • Loading branch information
phprus committed Sep 4, 2024
1 parent 21a3a36 commit 4374e1d
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 2 deletions.
6 changes: 4 additions & 2 deletions include/fmt/std.h
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,8 @@ FMT_BEGIN_NAMESPACE
FMT_EXPORT
template <typename T, typename E, typename Char>
struct formatter<std::expected<T, E>, Char,
std::enable_if_t<is_formattable<T, Char>::value &&
std::enable_if_t<(std::is_void<T>::value ||
is_formattable<T, Char>::value) &&
is_formattable<E, Char>::value>> {
FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
return ctx.begin();
Expand All @@ -292,7 +293,8 @@ struct formatter<std::expected<T, E>, Char,

if (value.has_value()) {
out = detail::write<Char>(out, "expected(");
out = detail::write_escaped_alternative<Char>(out, *value);
if constexpr (!std::is_void<T>::value)
out = detail::write_escaped_alternative<Char>(out, *value);
} else {
out = detail::write<Char>(out, "unexpected(");
out = detail::write_escaped_alternative<Char>(out, value.error());
Expand Down
2 changes: 2 additions & 0 deletions test/std-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ TEST(std_test, optional) {

TEST(std_test, expected) {
#ifdef __cpp_lib_expected
EXPECT_EQ(fmt::format("{}", std::expected<void, int>{}), "expected()");
EXPECT_EQ(fmt::format("{}", std::expected<int, int>{1}), "expected(1)");
EXPECT_EQ(fmt::format("{}", std::expected<int, int>{std::unexpected(1)}),
"unexpected(1)");
Expand All @@ -163,6 +164,7 @@ TEST(std_test, expected) {
EXPECT_FALSE(
(fmt::is_formattable<std::expected<int, unformattable2>>::value));
EXPECT_TRUE((fmt::is_formattable<std::expected<int, int>>::value));
EXPECT_TRUE((fmt::is_formattable<std::expected<void, int>>::value));
#endif
}

Expand Down

0 comments on commit 4374e1d

Please sign in to comment.