Skip to content

Commit a6d1684

Browse files
Add support for C++20 format API
Signed-off-by: Christian Parpart <[email protected]>
1 parent eff3f40 commit a6d1684

File tree

3 files changed

+38
-6
lines changed

3 files changed

+38
-6
lines changed

.github/workflows/build.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ jobs:
3535
strategy:
3636
fail-fast: false
3737
matrix:
38-
os: [ubuntu-24.04, ubuntu-22.04, ubuntu-20.04]
38+
os: [ubuntu-24.04, ubuntu-22.04]
3939
cxx: [20]
4040
build_type: ["RelWithDebInfo"]
4141
llvm_version:

include/boxed-cpp/boxed.hpp

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -207,19 +207,30 @@ struct hash<boxed::detail::boxed<T, U>>
207207
} // namespace std
208208
// {{{ fmtlib integration
209209
// clang-format off
210-
#if __has_include(<fmt/format.h>)
210+
#if __has_include(<format>)
211+
#include <format>
212+
// clang-format on
211213

214+
template <typename Type, typename Tag>
215+
struct std::formatter<boxed::detail::boxed<Type, Tag>>: std::formatter<Type>
216+
{
217+
auto format(boxed::detail::boxed<Type, Tag> const& val, auto& ctx) const
218+
{
219+
return std::formatter<Type>::format(val.value, ctx);
220+
}
221+
};
222+
#elif __has_include(<fmt/format.h>)
223+
224+
// clang-format off
212225
#include <fmt/format.h>
213226
// clang-format on
214227

215228
template <typename Type, typename Tag>
216-
struct fmt::formatter<boxed::detail::boxed<Type, Tag>>
229+
struct fmt::formatter<boxed::detail::boxed<Type, Tag>>: fmt::formatter<Type>
217230
{
218-
constexpr auto parse(fmt::format_parse_context& ctx) { return ctx.begin(); }
219-
220231
auto format(boxed::detail::boxed<Type, Tag> const& val, fmt::format_context& ctx) const
221232
{
222-
return fmt::format_to(ctx.out(), "{}", val.value);
233+
return fmt::formatter<Type>::format(val.value, ctx);
223234
}
224235
};
225236

test-boxed-cpp.cpp

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,3 +215,24 @@ TEST_CASE("advanced")
215215
REQUIRE(x_coord(rho, theta, phi) == x_coord(theta, phi, rho));
216216
REQUIRE(x_coord(phi, theta, rho) == x_coord(phi, theta, rho));
217217
}
218+
219+
#ifdef __has_include
220+
#if __has_include(<version>)
221+
#include <version>
222+
#endif
223+
#endif
224+
225+
#if defined(__cpp_lib_format) // && __cpp_lib_format >= 202207LL
226+
TEST_CASE("formatter")
227+
{
228+
auto constexpr l = Length { 3 };
229+
auto constexpr f = From { 2 };
230+
auto constexpr t = To { 4 };
231+
auto constexpr bd = BoxedDouble { 3.14 };
232+
233+
REQUIRE(std::format("{}", l) == "3");
234+
REQUIRE(std::format("{}", f) == "2");
235+
REQUIRE(std::format("{}", t) == "4");
236+
REQUIRE(std::format("{}", bd) == "3.14");
237+
}
238+
#endif

0 commit comments

Comments
 (0)