【问题标题】:How to make `boost::stacktrace` formattable with `fmt::format`如何使用 `fmt::format` 使 `boost::stacktrace` 可格式化
【发布时间】:2021-08-04 22:57:12
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    只有三件小事:

    1. 缺少/错误的标题。您需要包含 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

    【讨论】:

    • 酷,boost::stacktrace::frame const 抓住了我,其余的只是一些蹩脚的混淆。我会跟进最终版本以供参考。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    • 2017-10-30
    • 2021-07-28
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多