【问题标题】:Custom {fmt} formatting function with compile time format string checking带有编译时格式字符串检查的自定义 {fmt} 格式化函数
【发布时间】:2019-09-13 10:08:05
【问题描述】:

我有自己的日志记录功能。我想用libfmt来格式化日志参数,例如:

log_error("Error on read: {}", errMsg);

但是,编译时格式字符串检查似乎只有在我直接调用打印/格式化函数时才有效,而不是在我的日志函数中调用它们:

#include <fmt/format.h>

template<typename ...Args>
void log_error(fmt::string_view format, const Args& ...args) {
    // Log function stripped down to the essentials for this example
    fmt::print(format, args...);
}

int main()
{
    // No errors on this line
    log_error(FMT_STRING("Format with too few and wrong type arguments {:d}"), "one", 2.0);
    // Compile errors on the next line
    // fmt::print(FMT_STRING("Format with too few and wrong type arguments {:d}"), "one", 2.0);
}

上面的代码和错误(如果第二行没有注释的话)可以在godbolt看到

有没有办法让这个编译时格式检查在我自己的日志函数中工作?

【问题讨论】:

    标签: c++ fmt


    【解决方案1】:

    您可以将格式字符串作为另一个模板传递给自定义log_error 实现。示例:

    template<typename Str, typename ...Args>
    void log_error(const Str& format, const Args& ...args) {
        fmt::print(format, args...);
    }
    

    这会产生与直接调用相同的错误。

    【讨论】:

      猜你喜欢
      • 2021-07-08
      • 1970-01-01
      • 2021-12-02
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-09
      • 2012-08-28
      相关资源
      最近更新 更多