宏参数上的 Foreach 宏 [英] Foreach macro on macros arguments

查看:25
本文介绍了宏参数上的 Foreach 宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在宏参数上编写宏 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);

这篇关于宏参数上的 Foreach 宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆