序列的宏递归扩展
是否可以定义一个 C/C++ 宏“BUILD(a, i)
”,它将扩展为“x[0], x[1], x[2], ... , x[i]
" ?就像看起来
#define BUILD(x, 0) x[0]
#define BUILD(x, 1) x[0], x[1]
#define BUILD(x, 2) x[0], x[1], x[2]
...
BOOST_PP_ENUM_PARAMS 可以完成这项工作。我想我可以只是#include boost,但我有兴趣知道它如何以及为什么工作,任何人都可以解释吗?
我想调用一个函数 f(int, ...)
,它接受 N 个 int 参数 x[i]
, 0 <= i << N。其中 N 已知为 ceil(sizeof(A) / sizeof(B))。不幸的是,我不能使用可变参数或模板。
Is it possible to define a C/C++ macro "BUILD(a, i)
" which expands to "x[0], x[1], x[2], ..., x[i]
" ? Like in
#define BUILD(x, 0) x[0]
#define BUILD(x, 1) x[0], x[1]
#define BUILD(x, 2) x[0], x[1], x[2]
...
It seems BOOST_PP_ENUM_PARAMS could do the job. I suppose I could just #include boost, but I'm interested in knowing how and why it works, anyone can explain?
I would like to call a function f(int, ...)
which takes N int arguments x[i]
, 0 <= i < N. Where N is known to be ceil(sizeof(A) / sizeof(B))
. So unfortunately, I cannot use varargs or templates.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有可能,但是你必须做一些手工工作并且有一个上限。
请注意,
i
应该是整数文字,而不是常量计算值。顺便说一句,预处理器比通常情况下更强大,但使用该功能非常棘手。 Boost 提供了一个库,可以简化一些事情,包括迭代。请参阅 Boost 预处理器库。还有另一个图书馆可以存放此类东西,但我现在记不起它的名字了。
编辑:boost 预处理器库使用类似的技术。通过额外的技巧来解决一些极端情况问题,在更高级别的设施之间共享实现宏,解决编译器错误等...通常的提升复杂性,这在通用库的上下文中是正常的,但有时会妨碍轻松理解实施原则。也许最引人注目的技巧是添加一个间接级别,以便如果第二个参数可以是宏,则它会被扩展。也就是说,
一个人可以拨打电话,
而我所公开的内容是不可能的。
It is possible, but you have to do some manual work and have an upper limit.
And note that
i
should be an integer literal, not a constant computed value.BTW, the preprocessor is more powerful than what is usually though, but the use of that power is quite tricky. Boost provides a library which eases some things, including iteration. See Boost Preprocessor Library. There is another library for such things, but its name escapes me at the moment.
Edit: The boost preprocessor library uses a similar technique. With additional tricks to solve some corner cases problems, share implementation macros between higher level facilities, work around compiler bugs, etc... the usual boost complexity which is normal in the context of a general purpose library but which at times prevents easy understanding of the implementation principles. Probably the most noticeable trick is to add an indirection level so that if the second parameter can be a macro, it is expanded. I.e. with
one can make the call
which isn't possible with what I exposed.
不,不是——宏不能递归。还有你发布的宏
不是可变参数,这意味着“具有不同数量的参数”。
No, it isn't - macros cannot be recursive. And the macros you posted
are not variadic, which means "having different numbers of parameters".
好的,
我遇到了同样的问题,我的目标是使用宏打印 N 字节数组的所有值。我想你也有几乎同样的问题。如果是这样的话,这个解决方案应该适合未来类似的问题。
Ok,
I had the same problem, My aim was to print all the values of an array of N bytes using macros. I assume you had pretty much the same problem. If this was the case, this solution should suit future similar problems.