7

我想在 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);
}

哪个产生正确./example.cpp,20, invalid squishiness: 42

在我看来,我很接近。我认为剩下的就是让log函数采用默认参数source_location(我知道source_location::current()作为默认参数是一个很好的做法)。我收到以下错误:

:12:99: 错误: 参数 'args' 缺少默认参数

这甚至可以混合可变参数模板和参数的默认参数吗?如果是这样,怎么做?

此外,有没有办法将"{},{}, "部分添加到编译时format字符串以产生另一个编译时字符串(用作格式)?

4

1 回答 1

17

您可以使用表示格式字符串和位置的结构来执行此操作:

#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);
}

这打印:

./example.cpp:26: invalid squishiness: 42

神箭:https ://godbolt.org/z/4aMKcW

于 2021-02-26T04:39:18.303 回答