使用格式化时有没有办法扩展spdlog以支持自定义结构作为项目{}?
所以当我有一个
struct p {
int x;
int y;
int z;
};
p my_p;
Run Code Online (Sandbox Code Playgroud)
我想要做
spdlog::info("p = {}", my_p);
// after registering some kind of formatter object for {p}
Run Code Online (Sandbox Code Playgroud)
代替
spdlog::info("p = (x={}, y={}, z={})", my_p.x, my_p.y, my_p.z);
Run Code Online (Sandbox Code Playgroud)
接受的答案不再适用于较新版本的 spdlog,fmt现在需要专门化formatter<T>(有关详细信息,请参阅https://fmt.dev/latest/api.html#udt )。
使用您的p结构,这是格式化程序:
#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);
}
};
Run Code Online (Sandbox Code Playgroud)
该parse方法用于读取最终的格式规范,如果您不需要它们,您可以简单地返回ctx.end()并跳过规范,如示例中所示。
#include "spdlog/spdlog.h"
#include "spdlog/fmt/ostr.h" // must be included
class some_class {};
std::ostream& operator<<(std::ostream& os, const some_class& c)
{
return os << "some_class";
}
Run Code Online (Sandbox Code Playgroud)
请参阅https://github.com/gabime/spdlog/wiki/1.-QuickStart#log-user-define-objects