Skip to content

Commit

Permalink
Add support for C++20 format API
Browse files Browse the repository at this point in the history
Signed-off-by: Christian Parpart <[email protected]>
  • Loading branch information
christianparpart committed Sep 25, 2024
1 parent eff3f40 commit e5efcaf
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 5 deletions.
21 changes: 16 additions & 5 deletions include/boxed-cpp/boxed.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -207,19 +207,30 @@ struct hash<boxed::detail::boxed<T, U>>
} // namespace std
// {{{ fmtlib integration
// clang-format off
#if __has_include(<fmt/format.h>)
#if __has_include(<format>)
#include <format>
// clang-format on

template <typename Type, typename Tag>
struct std::formatter<boxed::detail::boxed<Type, Tag>>: std::formatter<Type>
{
auto format(boxed::detail::boxed<Type, Tag> const& val, auto& ctx) const
{
return std::formatter<Type>::format(val.value, ctx);
}
};
#elif __has_include(<fmt/format.h>)

// clang-format off
#include <fmt/format.h>
// clang-format on

template <typename Type, typename Tag>
struct fmt::formatter<boxed::detail::boxed<Type, Tag>>
struct fmt::formatter<boxed::detail::boxed<Type, Tag>>: fmt::formatter<Type>
{
constexpr auto parse(fmt::format_parse_context& ctx) { return ctx.begin(); }

auto format(boxed::detail::boxed<Type, Tag> const& val, fmt::format_context& ctx) const
{
return fmt::format_to(ctx.out(), "{}", val.value);
return fmt::formatter<Type>::format(val.value, ctx);
}
};

Expand Down
21 changes: 21 additions & 0 deletions test-boxed-cpp.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -215,3 +215,24 @@ TEST_CASE("advanced")
REQUIRE(x_coord(rho, theta, phi) == x_coord(theta, phi, rho));
REQUIRE(x_coord(phi, theta, rho) == x_coord(phi, theta, rho));
}

#ifdef __has_include
#if __has_include(<version>)
#include <version>
#endif
#endif

#if defined(__cpp_lib_format) // && __cpp_lib_format >= 202207LL
TEST_CASE("formatter")
{
auto constexpr l = Length { 3 };
auto constexpr f = From { 2 };
auto constexpr t = To { 4 };
auto constexpr bd = BoxedDouble { 3.14 };

REQUIRE(std::format("{}", l) == "3");
REQUIRE(std::format("{}", f) == "2");
REQUIRE(std::format("{}", t) == "4");
REQUIRE(std::format("{}", bd) == "3.14");
}
#endif

0 comments on commit e5efcaf

Please sign in to comment.