Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend spdlog for custom type

Tags:

c++

spdlog

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);
like image 271
pmf Avatar asked May 16 '26 10:05

pmf


1 Answers

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.

like image 61
aghidini Avatar answered May 17 '26 23:05

aghidini