Foreach macro on macros arguments(宏参数上的 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 宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:宏参数上的 Foreach 宏


基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01