Skip to content
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
20 changes: 20 additions & 0 deletions include/fmt/std.h
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,26 @@ struct formatter<std::expected<T, E>, Char,
return out;
}
};

template <typename E, typename Char>
struct formatter<std::unexpected<E>, Char,
std::enable_if_t<is_formattable<E, Char>::value>> {
FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
return ctx.begin();
}

template <typename FormatContext>
auto format(const std::unexpected<E>& value, FormatContext& ctx) const
-> decltype(ctx.out()) {
auto out = ctx.out();

out = detail::write<Char>(out, "unexpected(");
out = detail::write_escaped_alternative<Char>(out, value.error(), ctx);

*out++ = ')';
return out;
}
};
#endif // __cpp_lib_expected

#ifdef __cpp_lib_source_location
Expand Down
10 changes: 9 additions & 1 deletion test/std-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
#include <string>
#include <vector>

#include "fmt/os.h" // fmt::system_category
#include "fmt/os.h" // fmt::system_category
#include "fmt/ranges.h"
#include "gtest-extra.h" // StartsWith

Expand Down Expand Up @@ -176,6 +176,14 @@ TEST(std_test, expected) {
(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));

EXPECT_EQ(fmt::format("{}", std::unexpected{1}), "unexpected(1)");
EXPECT_EQ(fmt::format("{}", std::unexpected<std::string>{"test"}),
"unexpected(\"test\")");

EXPECT_EQ(fmt::format("{}", std::unexpected<char>{'a'}), "unexpected('a')");

EXPECT_FALSE((fmt::is_formattable<std::unexpected<unformattable2>>::value));
#endif
}

Expand Down