我想在C ++中创建一个简单的日志函数,将代码位置添加到日志消息前面。我想尽可能避免使用宏以及
请注意,
我可以通过
我从this开始。目前,我有以下内容:
__FILE__
和__LINE__
的用法。请注意,
format
字符串始终是编译时字符串,并且我希望在编译时进行尽可能多的计算(目标机器是小型MCU)。我可以通过
experimental/source_location
使用C++20 source_location
特性。我也可以使用{fmt}。我从this开始。目前,我有以下内容:
#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);
}
这个错误信息是 ./example.cpp,20, invalid squishiness: 42
,请问您需要什么样的结果?
看起来我已经很接近了。我认为还剩下的部分就是让log
函数接受一个默认参数source_location
(我理解source_location::current()
作为默认参数是一个好习惯)。不过我遇到了以下错误:
:12:99: error: missing default argument on parameter 'args'
是否可能将可变参数模板和参数的默认值混合使用?如果可以,应该如何操作?
此外,是否有一种方法可以将"{},{}, "
部分附加到编译时的format
字符串前面,以产生另一个编译时字符串(用作格式)?
log(FMT_STRING("invalid squishiness: {} {}"), 42);
,它将不会产生编译时错误。 - Alexander Chen