自定义 {fmt} 格式化函数,具有编译时格式字符串检查功能

Custom {fmt} formatting function with compile time format string checking

本文关键字:编译 格式 字符串 功能 检查 fmt 格式化 函数 自定义      更新时间:2023-10-16

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

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

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

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

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