Skip to content

Commit 7977fa4

Browse files
committed
Add std::formatter support for variant2 and corresponding tests
1 parent 84558aa commit 7977fa4

2 files changed

Lines changed: 40 additions & 0 deletions

File tree

include/dice/template-library/variant2.hpp

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#include <compare>
66
#include <cstdint>
77
#include <exception>
8+
#include <format>
89
#include <functional>
910
#include <type_traits>
1011
#include <utility>
@@ -903,4 +904,28 @@ namespace dice::template_library {
903904

904905
} // namespace dice::template_library
905906

907+
namespace std {
908+
template<typename T, typename U, typename CharT>
909+
struct formatter<::dice::template_library::variant2<T, U>, CharT> {
910+
template<typename Ctx>
911+
constexpr auto parse(Ctx &parse_ctx) {
912+
return parse_ctx.begin();
913+
}
914+
915+
template<typename Ctx>
916+
auto format(::dice::template_library::variant2<T, U> const &var, Ctx &format_ctx) const {
917+
if (var.valueless_by_exception()) {
918+
return std::format_to(format_ctx.out(), "var2<valueless-by-exception>");
919+
}
920+
return ::dice::template_library::visit([&format_ctx]<typename X>(X const &value) {
921+
if constexpr (std::formattable<X, CharT>) {
922+
return std::format_to(format_ctx.out(), "var2<{}>", value);
923+
} else {
924+
return std::format_to(format_ctx.out(), "var2<non-formattable>");
925+
}
926+
}, var);
927+
}
928+
};
929+
} // namespace std
930+
906931
#endif // DICE_TEMPLATELIBRARY_VARIANT2_HPP

tests/tests_variant2.cpp

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,4 +289,19 @@ TEST_SUITE("variant2") {
289289
static_assert(!std::is_trivially_destructible_v<var2>);
290290
static_assert(!std::is_trivially_copyable_v<var2>);
291291
}
292+
293+
TEST_CASE("formatting") {
294+
struct non_formattable {
295+
};
296+
297+
CHECK(std::format("{}", variant2<int, double>{42}) == "var2<42>");
298+
CHECK(std::format("{}", variant2<int, double>{1.5}) == "var2<1.5>");
299+
CHECK(std::format("{}", variant2<int, non_formattable>{5}) == "var2<5>");
300+
CHECK(std::format("{}", variant2<int, non_formattable>{non_formattable{}}) == "var2<non-formattable>");
301+
302+
variant2<int, make_valueless> valueless{};
303+
try { valueless = make_valueless{std::nothrow}; } catch (...) {
304+
}
305+
CHECK(std::format("{}", valueless) == "var2<valueless-by-exception>");
306+
}
292307
}

0 commit comments

Comments
 (0)