gal*_*h92 7 c++ default-arguments variadic-templates fmt
我想在 C++ 中创建一个简单的日志函数,它将代码位置添加到日志消息中。我想避免使用宏以及__FILE__&的使用__LINE__。
请注意,该format字符串始终是编译时字符串,我希望在编译时进行尽可能多的计算(目标机器是一个小型 MCU)。
我可以source_location通过experimental/source_location. 我也可以使用{fmt}。
我从这个开始。目前,我有以下几点:
#include <fmt/format.h>
#include <experimental/source_location>
using source_location = std::experimental::source_location;
void vlog(fmt::string_view format, fmt::format_args args)
{
fmt::vprint(format, args);
}
template <typename S, typename... Args>
void log(const S& format, const source_location& location, Args&&... args)
{
vlog(format, fmt::make_args_checked<fmt::string_view, uint32_t, Args...>(format, location.file_name(), location.line(), args...));
}
#define MY_LOG(format, ...) log(FMT_STRING("{},{}, " format), source_location::current(), __VA_ARGS__)
int main() {
MY_LOG("invalid squishiness: {}", 42);
}
Run Code Online (Sandbox Code Playgroud)
哪个产量正确./example.cpp,20, invalid squishiness: 42。
在我看来,我已经很接近了。我认为剩下的就是让log函数采用默认参数source_location(我理解source_location::current()作为默认参数是一种很好的做法)。虽然我收到以下错误:
:12:99: 错误:缺少参数“args”的默认参数
这甚至可以混合可变参数模板和参数的默认参数吗?如果是这样,如何?
另外,有没有办法将"{},{}, "部分添加到编译时format字符串以产生另一个编译时字符串(用作格式)?
vit*_*aut 15
您可以使用表示格式字符串和位置的结构来实现:
#include <fmt/core.h>
#include <source_location>
struct format_string {
fmt::string_view str;
std::source_location loc;
format_string(
const char* str,
const std::source_location& loc =
std::source_location::current()) : str(str), loc(loc) {}
};
void vlog(const format_string& format, fmt::format_args args) {
const auto& loc = format.loc;
fmt::print("{}:{}: ", loc.file_name(), loc.line());
fmt::vprint(format.str, args);
}
template <typename... Args>
void log(const format_string& format, Args&&... args) {
vlog(format, fmt::make_format_args(args...));
}
int main() {
log("invalid squishiness: {}", 42);
}
Run Code Online (Sandbox Code Playgroud)
这打印:
./example.cpp:26: invalid squishiness: 42
Run Code Online (Sandbox Code Playgroud)
Godbolt:https ://godbolt.org/z/4aMKcW
| 归档时间: |
|
| 查看次数: |
623 次 |
| 最近记录: |