C++ 重载宏

标签 c++ macros

我看到了重载宏的不同解决方案和变通方法。但是我在这方面似乎有困难。
我有一个打印到 visual studio 调试器的 PRINT_DEBUG 宏:

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

现在说我想像这样重载它:

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

这当然行不通,因为它会选择第一个宏。
所以我检查了其他主题并找到了这个solution这是我想出的:

#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__)

我正在尝试像这样使用它:

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

我真的必须根据我拥有的参数数量对每个参数进行硬编码吗?还是有什么创造性的方法可以做到这一点?

我发现的唯一解决方法是只有一个:

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

假设我只想打印一条消息,我必须在 mvsc 编译器中传递第二个参数:

PRINT_DEBUG("My message", NULL);

任何帮助将不胜感激!提前致谢!

最佳答案

至少在 GCC 中你不需要重载任何东西来解决这个问题:

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

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

In standard C, you are not allowed to leave the variable argument out entirely; but you are allowed to pass an empty argument. For example, this invocation is invalid in ISO C, because there is no comma after the string:

debug ("A message")

GNU CPP permits you to completely omit the variable arguments in this way. In the above examples, the compiler would complain, though since the expansion of the macro still has the extra comma after the format string.

To help solve this problem, CPP behaves specially for variable arguments used with the token paste operator, ‘##’. If instead you write

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

and if the variable arguments are omitted or empty, the ‘##’ operator causes the preprocessor to remove the comma before it. If you do provide some variable arguments in your macro invocation, GNU CPP does not complain about the paste operation and instead places the variable arguments after the comma. Just like any other pasted macro argument, these arguments are not macro expanded.

关于C++ 重载宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49834539/

相关文章:

macros - 使用 Racket 宏生成 require-clauses

c - 如何控制C宏优先级

c++ - 保存 C++ 预处理器宏的原始值

macros - 是否可以从宏中发出 Rust 属性?

c++ - 如何从已编译的C文件(使用Borland C++编译)中查看程序代码

c++ - 为什么将 const 添加到从迭代器中提取的这对字符串中?

c++ - 将 boost::array<> 打印到标准输出

c++ - operator= 的返回类型 - 引用还是值?

您可以在宏中将粘贴的标记大写吗?

java - 用于 C/C++ 和 Java 的 Eclipse IDE