使用编译时格式字符串检查的自定义 {fmt} 格式化函数。

7
我已经有了自己的日志记录函数。我想使用libfmt格式化日志参数,例如:
log_error("Error on read: {}", errMsg);

然而,编译时格式字符串检查似乎只在我直接调用print/format函数时起作用,而不是在我调用log函数时起作用:

#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上查看。
是否有办法让这个编译时格式检查在我的自定义日志函数中起作用?
1个回答

5
您可以将格式字符串作为另一个模板传递给自定义的log_error实现。例如:
template<typename Str, typename ...Args>
void log_error(const Str& format, const Args& ...args) {
    fmt::print(format, args...);
}

这会导致与直接调用相同的错误。

这似乎不再适用于 fmt 版本 9:'format' 不是常量表达式。 - Mike

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接