7

我有自己的日志记录功能。我想使用 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上看到

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

4

1 回答 1

5

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

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

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

于 2019-09-13T10:12:36.817 回答