我正在努力让 boost 的堆栈跟踪库与 fmt 进行互操作,问题似乎是我无法完全专门化 boost::stacktrace::basic_stacktrace 。有人知道根本问题是什么吗?
#include <fmt/core.h>
#include <boost/stacktrace.hpp>
using BoostTraceStackFrame = std::remove_reference_t<decltype(boost::stacktrace::stacktrace().as_vector().front())>;
template <> struct fmt::formatter<BoostTraceStackFrame> : formatter<string_view>
{
template <typename FORMAT_CONTEXT> auto format(const BoostTraceStackFrame &rhs, FORMAT_CONTEXT &ctx)
{
return fmt::format(ctx.out(), "{}:{}\n", rhs.source_file(), rhs.source_line());
}
};
using BoostTraceType = std::remove_reference_t<decltype(boost::stacktrace::stacktrace())>;
template <> struct fmt::formatter<BoostTraceType> : formatter<string_view>
{
//possibly BoostTraceType = boost::stacktrace::basic_stacktrace ?
template <typename FORMAT_CONTEXT> auto format(const BoostTraceType &rhs, FORMAT_CONTEXT &ctx)
{
return fmt::format(ctx.out(), "{}", fmt::join(rhs.as_vector(), "\n"));
}
};
int main()
{
auto trace = boost::stacktrace::stacktrace();
fmt::print("Foo trace {}",trace);
}
最佳答案
只有三件小事:
header 丢失/错误。您需要包含
fmt/ranges.h
才能支持格式化范围。错误的过载。用于格式化为迭代器的函数是
fmt::format_to
,而不是fmt::format
。这些:
using BoostTraceStackFrame = std::remove_reference_t<decltype(boost::stacktrace::stacktrace().as_vector().front())>;
using BoostTraceType = std::remove_reference_t<decltype(boost::stacktrace::stacktrace())>;
是相当冗长的写作方式:
using BoostTraceStackFrame = boost::stacktrace::frame;
using BoostTraceType = boost::stacktrace::stacktrace;
特别是,问题在于您编写第一个代码的方式是 boost::stacktrace::frame const
,而它不需要是 const
。
关于c++ - 如何使用 `boost::stacktrace` 使 `fmt::format` 格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67539887/