Is there a way to extend spdlog to support a custom struct as an item when formatting using {}?
So when I have a
struct p {
int x;
int y;
int z;
};
p my_p;
I want to do
spdlog::info("p = {}", my_p);
// after registering some kind of formatter object for {p}
instead of
spdlog::info("p = (x={}, y={}, z={})", my_p.x, my_p.y, my_p.z);
The accepted answer does not work anymore with newer versions of spdlog, fmt now requires specializing formatter<T> (see https://fmt.dev/latest/api.html#udt for details).
Using your p struct this is the formatter:
#include <spdlog/fmt/bundled/format.h>
template<>
struct fmt::formatter<p> {
constexpr auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
return ctx.end();
}
template <typename FormatContext>
auto format(const p& input, FormatContext& ctx) -> decltype(ctx.out()) {
return format_to(ctx.out(),
"(x={}, y={}, z={})",
input.x, input.y, input.z);
}
};
The parse method is used to read eventual format specifications, if you don't need them you can simply return ctx.end() and skip specifications like in the sample.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With