More specifically, how to insert a format string into another format string inside a macro? In other words, how to write
#define PRINT_ERROR(x, ...) do { if (DEBUG) fprintf(stderr, std::format("Error: {}\n", x).c_str(), __VA_ARGS__); } while (0)
without using sprintf
or std::format
(only available with /std:c++latest
flag in MSVC as of the date of writing), i.e. not formatting the string twice in the first place?
#define PRINT_ERROR(x, ...) do { if (DEBUG) fputs("Error: ", stderr); fprintf(stderr, x, __VA_ARGS__); fputs("\n", stderr); } while (0)
is better, but that's three function calls instead of one.
Example:
const char* format = "%s %s!";
PRINT_ERROR(format, "Hello", "World");
Output:
Error: Hello World!
P.S.
I'm wrapping the macro inside a function anyway, but still want to have a fully functional macro for the sake of it.
class Debug final
{
public:
template<typename... Args>
static void Error(const std::string& fmt, Args... args) { PRINT_ERROR(fmt.c_str(), args...); }
// ...
}