Home > database >  How to forward the macro args to format func?
How to forward the macro args to format func?

Time:08-28

#define LOG_INFO(str, ...)                                              \
  logger.NewLogStateMent(__FILE__, __LINE__,                            \
                         fver::base::log::Logger::LogLevel::kInfo, str, \
                         ##__VA_ARGS__)
void NewLogStateMent(const char* filename, const int len, LogLevel lev, ...) {
  std::cout << fmt::format("{} {} {} {} {}", filename, lne, lev, ...);
}
// use case
int main () {
  LOG_INFO("hello, world %d", 1);
}

Now i want to this LOG_INFO(str, ...) to a fmt::format();

But the Gcc give me a lot of errors gcc version: 12.2.0

c version: c 17

How can i finish it?

Please help me!

CodePudding user response:

Something along these lines:

#define LOG_INFO(str, ...) \
  NewLogStateMent(__FILE__, __LINE__, \
                         "info", str, \
                         ##__VA_ARGS__)

template <typename... Args>
void NewLogStateMent(const char* filename, const int line, const char* level,
                     const std::string& format_str, Args&&... args) {
  std::cout << fmt::format("{} {} {} ", filename, line, level)
            << fmt::format(fmt::runtime(format_str), std::forward<Args>(args)...);
}

// use case
int main () {
  LOG_INFO("hello {} world", 1);
}

Demo

CodePudding user response:

Here's how to do it with compile-time checks (https://godbolt.org/z/EE1zxcdrK):

#include <fmt/core.h>

#define LOG_INFO(str, ...)                                              \
  NewLogStatement(__FILE__, __LINE__, "info", str, ##__VA_ARGS__)

template <typename... T>
void NewLogStatement(const char* filename, int line, const char* level,
                     fmt::format_string<T...> fmt, T&&... args) {
  fmt::print("{} {} {} ", filename, line, level);
  fmt::print(fmt, std::forward<T>(args)...);
}

int main () {
  LOG_INFO("hello {} world", 1);
}
  • Related