C ++ macro overload

I have seen various solutions and workarounds for macro overloading. But I seem to have difficulty with this. I have a macro PRINT_DEBUGthat prints to a visual studio debugger:

#define DEBUG_PRINT(message, ...)   _RPTN(0, message "\n", __VA_ARGS__)

Now say that I want to overload it like this:

#define DEBUG_PRINT(message)        _RPT0(0, message "\n")
#define DEBUG_PRINT(message, ...)   _RPTN(0, message "\n", __VA_ARGS__)

This, of course, will not work, as he will pick up the first macro.
So I checked other topics and found this solution , and here is what I came up with:

#define PRINT_DEBUG(...) _DEBUG_PRINT_SELECT(__VA_ARGS__, _DEBUG_PRINT2, _DEBUG_PRINT1, ...) (__VA_ARGS__)

#define _DEBUG_PRINT_SELECT(_1, _2, NAME, ...) NAME

#define _DEBUG_PRINT1(message)      _RPT0(0, message "\n")
#define _DEBUG_PRINT2(message, ...) _RPTN(0, message "\n", __VA_ARGS__)

I am trying to use it like this:

PRINT_DEBUG("My message");
PRINT_DEBUG("My message %s", someString);
PRINT_DEBUG("My message %s %d", someString, someValue);

Do I really need to hard code each of them depending on the number of arguments I have? or is there a creative way to do this?

The only work I found was just a single:

#define PRINT_DEBUG(message, ...)   _RPTN(0, message "\n", __VA_ARGS__);

And I will say that I want to print only the message, I need to pass the second parameter in the mvsc compilers:

PRINT_DEBUG("My message", NULL);

! !

+4
2

, GCC -, :

#define DEBUG_PRINT(message, ...)   _RPTN(0, message "\n", ## __VA_ARGS__)

https://gcc.gnu.org/onlinedocs/gcc/Variadic-Macros.html:

C ; . , ISO C, :

debug ("A message")

GNU CPP . , , - .

, CPP , paste token, '##.

#define debug(format, ...) fprintf (stderr, format, ## __VA_ARGS__)

, ## . , GNU CPP . , , .

+2

, , , , . " " , .
.

#ifdef Debug
#define PRINT_DEBUG PrintDebugMessage
    enum DebugLevel {SERIOUS, MILD, IRRITATING, MISLEADING, etc};
    void PrintDebugMessage(message);
    void PrintDebugMessage(message, ...);
    void PrintDebugMessage(message, DebugLevel, ...);
    // and so on
#else
    // do nothing
    #define DebugPrint(...) 
#endif

PrintDebugMessage , .

0

Source: https://habr.com/ru/post/1696182/


All Articles