宏参数上的 Foreach 宏

2021-12-26 00:00:00 c macros foreach c++

我想知道是否可以在宏参数上编写宏 foreach.这是想要做的:

I wonder if it is possible to write a macro foreach on macros arguments. Here is what want to do:

#define PRINT(a) printf(#a": %d", a)
#define PRINT_ALL(...) ? ? ? THE PROBLEM ? ? ? 

以及可能的用法:

int a = 1, b = 3, d = 0;
PRINT_ALL(a,b,d);

这是我目前取得的成绩

#define FIRST_ARG(arg,...) arg
#define AFTER_FIRST_ARG(arg,...) , ##__VA_ARGS__     
#define PRINT(a) printf(#a": %d", a)
#define PRINT_ALL PRINT(FIRST_ARG(__VA_ARGS__)); PRINT_ALL(AFTER_FIRST_ARG(__VA_ARGS__))

这是一个递归宏,是非法的.另一个问题是递归的停止条件.

This is a recursive macro, which is illegal. And another problem with that is stop condition of recursion.

推荐答案

既然您接受预处理器具有 VA_ARGS(在 C99 中,但在当前 C++ 标准中没有),您可以使用 P99.它正是您所要求的:P99_FOR.它不需要来自 BOOST 的原始 ()()() 语法.界面只是

Since you are accepting that the preprocessor has VA_ARGS (in C99, but not in the current C++ standard) you can go with P99. It has exactly what you are asking for: P99_FOR. It works without the crude ()()() syntax from BOOST. The interface is just

P99_FOR(NAME, N, OP, FUNC,...) 

你可以用它来做类似的事情

and you can use it with something like

#define P00_SEP(NAME, I, REC, RES) REC; RES
#define P00_VASSIGN(NAME, X, I) X = (NAME)[I]
#define MYASSIGN(NAME, ...) P99_FOR(NAME, P99_NARG(__VA_ARGS__), P00_SEP, P00_VASSIGN, __VA_ARGS__)

MYASSIGN(A, toto, tutu);

相关文章