宏递归扩展到序列 [英] Macro recursive expansion to a sequence

查看:111
本文介绍了宏递归扩展到序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以定义一个C / C ++宏 BUILD(a,i),扩展为 x [0] [1],x [2],...,x [i] ?像

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]
...

似乎BOOST_PP_ENUM_PARAMS可以做这项工作。我想我只能#include boost,但我有兴趣知道如何和为什么它的工作原理,任何人都可以解释?

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?

我想调用一个函数 f(int,...),它接受N int个参数 x [i] ,0 <= i < N.其中N被认为是 ceil(sizeof(A)/ sizeof(B))。所以不幸的是,我不能使用varargs或模板。

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.

推荐答案

这是可能的,但你必须做一些手动工作,上限。

It is possible, but you have to do some manual work and have an upper limit.

#define BUILD0(x) x[0]
#define BUILD1(x) BUILD0(x), x[1]
#define BUILD2(x) BUILD1(x), x[2]
#define BUILD3(x) BUILD2(x), x[3]
#define BUILD(x, i) BUILD##i(x)

注意

BTW,预处理器比通常更强大,但是,使用这种力量是相当棘手的。 Boost提供了一个图书馆,可以减轻一些事情,包括迭代。请参见 Boost预处理器库。还有另一个库,这样的事情,但它的名字逃脱了我现在。

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.

编辑:boost预处理器库使用类似的技术。使用额外的技巧来解决一些角落的问题,在更高级别的设施之间共享实现宏,解决编译器错误等。通常的提升复杂性是正常的在通用目的库的上下文,但有时妨碍容易理解实施原则。可能最明显的窍门是添加间接层,以便如果第二个参数可以是一个宏,它会被扩展。也就是说

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

#define BUILD_(x, i) BUILD##i(x)
#define BUILD(x, i) BUILD_(x, i)

可以拨打电话

#define FOO 42
BUILD(x, FOO)

这是我所暴露的不可能。

which isn't possible with what I exposed.

这篇关于宏递归扩展到序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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