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 <vladislav@shchapov.ru>
  • Loading branch information
phprus committed Sep 3, 2024
1 parent 7a6a2a7 commit a74aee3
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
21 changes: 17 additions & 4 deletions include/fmt/std.h
Original file line number Diff line number Diff line change
Expand Up @@ -277,10 +277,22 @@ FMT_END_NAMESPACE
FMT_BEGIN_NAMESPACE

FMT_EXPORT

namespace detail {

template <typename T, typename Char>
struct is_expected_formattable : is_formattable<T, Char> {};

template <typename Char>
struct is_expected_formattable<void, Char> : std::true_type {};

} // namespace detail

template <typename T, typename E, typename Char>
struct formatter<std::expected<T, E>, Char,
std::enable_if_t<is_formattable<T, Char>::value &&
is_formattable<E, Char>::value>> {
struct formatter<
std::expected<T, E>, Char,
std::enable_if_t<detail::is_expected_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 +304,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 a74aee3

Please sign in to comment.