c++ - 如何使用 `boost::stacktrace` 使 `fmt::format` 格式化

标签 c++ boost stack-trace c++20 fmt

我正在努力让 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);
}

On godbolt

最佳答案

只有三件小事:

  1. header 丢失/错误。您需要包含 fmt/ranges.h 才能支持格式化范围。

  2. 错误的过载。用于格式化为迭代器的函数是 fmt::format_to,而不是 fmt::format

  3. 这些:

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/

相关文章:

C++ Boost Spirit,解析数据并存储最大值

查找多个字符串匹配的算法

python - 在变量内部完成递归

c++ - 为什么我得不到虚拟打印机的上下文?

c++ - 仅从一个模板参数查找特定模板。是否可以?

c++ - 通用 2D 点作为 C++ 中的输入

c++ - 在 C++ 中存储字符串时,char* 和 char 有什么区别?

c++ - 是否可以重用 binary_oarchive 实例?

javascript - 为什么 console.trace() 结果以 "anonymous function"结尾?那个功能是什么?

c++ - `myLibrary!__scrt_stub_for_is_c_termination_complete+0x12345`是什么符号