C 中是否有屏蔽宏参数中注释的通用方法?我知道括号可以用于此目的,但在添加括号导致宏输出中出现语法错误的情况下,这将不起作用。我听说 ({ }) 可以在 GCC 中屏蔽逗号,但我需要此代码也可以在 VC++ 中工作(最新版本之一,在宏中的逗号方面确实符合 C 标准)。在我的例子中,我也不能使用可变参数宏。
我想要做的具体情况是这样的(lengthof是在其他地方定义的宏)。我正在尝试为整个事情编写一个宏,因为这将被多次使用,并且拥有多宏解决方案将添加大量额外的测试代码。
#define TEST_UNFUNC(func, res_type, res_set, op_type, op_set) \
{ \
static const res_type res[] = res_set; \
static const op_type op[] = op_set; \
int i; \
for (i = 0; i < MIN(lengthof(res), lengthof(op)); i++) \
assert(func(op[i]) == res[i]); \
}
如果可能的话,我想要一个一般性的答案,而不仅仅是特定于这个特定宏的解决方法。
使用括号屏蔽逗号,然后通过特殊的
unparen
宏传递它们,在下面的示例中定义:
#include <stdio.h>
#define really_unparen(...) __VA_ARGS__
#define invoke(expr) expr
#define unparen(args) invoke(really_unparen args)
#define fancy_macro(a) printf("%s %s\n", unparen(a))
int main()
{
fancy_macro(("Hello", "World"));
}
这里的技巧是
invoke
宏强制进行额外的扩展,允许调用 really_unparen
,即使它在源代码中后面没有括号。
编辑:根据下面的评论,在这种情况下似乎没有必要。虽然我确信我遇到过需要它的情况有时...而且它不会造成伤害。
另一种解决方案是避免在开头放置逗号:
#define COMMA ,
#define FUNCTION_SIG(returnType, name, args) returnType name(args)
FUNCTION_SIG(int, add, int a COMMA int b);
扩展代码
int add(int a, int b);