自定义 {fmt} 格式化函数,具有编译时格式字符串检查功能
Custom {fmt} formatting function with compile time format string checking
我有自己的日志记录函数。我想使用 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...);
}
这会产生与直接调用相同的错误。
相关文章:
- 二叉排序树无法编译
- 编译时未启用intel oneApi CUDA支持
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 在C++标准中做格式好意味着代码可以编译
- 如何设置叮当格式的注释编译指示,以免触及多行doxygen注释?
- C++ 编译错误:gnu_printf是无法识别的格式函数类型
- 自定义 {fmt} 格式化函数,具有编译时格式字符串检查功能
- 不正确的printf格式指定器编译
- 编译用于创建boost.log格式的代码时出错
- 成功地编译成格式的程序是符合标准的
- 在编译时以 static_assert() 格式显示整数
- 一种在编译时用C++根据printf格式检查参数的可移植方法
- 以在编译时和运行时都可用的方式描述C++像素格式信息
- 在调试模式下编译时,丰富的编辑控件格式不起作用
- 使用constexpr进行基本编译时格式字符串检查
- c++ 11编译时调用printf的格式字符串字面值构造
- 编译复杂的(有很多引用的)ASN模式-证书请求格式(RFC4211)
- 当编译时数据格式和类型未知时,C++将数据读入内存
- GCC-如何使用FLV1(又名H.263)、MP3(格式和编解码器)和FLV(容器格式)编译FFMpeg
- 为什么这个格式错误的程序在 g++ 中编译得很好