带有编译时格式字符串检查的自定义 {fmt} 格式化函数
Custom {fmt} formatting function with compile time format string checking
我有自己的日志记录功能。我想用libfmt格式化日志参数,eg:
log_error("Error on read: {}", errMsg);
然而,编译时格式字符串检查似乎只有在我直接调用 print/format 函数时才有效,如果我在我的日志函数中调用它们则无效:
#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...);
}
这会产生与直接调用相同的错误。
我有自己的日志记录功能。我想用libfmt格式化日志参数,eg:
log_error("Error on read: {}", errMsg);
然而,编译时格式字符串检查似乎只有在我直接调用 print/format 函数时才有效,如果我在我的日志函数中调用它们则无效:
#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...);
}
这会产生与直接调用相同的错误。