使用C预处理程序的嵌套宏迭代 [英] Nested macro iteration with C preprocessor
问题描述
使用C预处理器,您可以具有某种高阶宏.像这样:
With the C preprocessor you can have some kind of high-order macros. Something like this:
#define ABC(f) f(a) f(b) f(c)
#define XY(f) f(x) f(y)
#define CODE(x) foo_ ## x
ABC(CODE)
#undef CODE
#define CODE(x) bar_ ## x
XY(CODE)
#undef CODE
输出为:
foo_a foo_b foo_c
bar_x bar_y
是否有一些技巧可以嵌套这样的迭代,以进行类似的事情?
Is there some trick to nest such iterations, to do something like this?
#define CODE(x) foo_ ## x
NEST(ABC, XY, CODE)
#undef CODE
所以输出将是:
foo_ax foo_ay foo_bx foo_by foo_cx foo_cy
尤其是,我希望ABC
和XY
的定义彼此独立,以便我仍然可以独立使用ABC
甚至可以做这样的事情:
In particular, I'd like to have the definitions of ABC
and XY
independent from each other, so that I can still use ABC
stand-alone or maybe do even something like this:
#define CODE(x) foo_ ## x
NEST(XY, KLMN, ABC, CODE)
#undef CODE
记录下来,这里是解决方案:
For the record, here the solution:
#include <boost/preprocessor/seq.hpp>
#define ABC (a) (b) (c)
#define XY (x) (y)
#define CODE(r, prod) BOOST_PP_CAT(foo_, BOOST_PP_SEQ_CAT(prod))
BOOST_PP_SEQ_FOR_EACH_PRODUCT(CODE, (ABC) (XY))
收益:
foo_ax foo_ay foo_bx foo_by foo_cx foo_cy
推荐答案
增强预处理器库提供了一些可以立即使用的宏.
The Boost Preprocessor Library offers several macros that can do this out of the box.
BOOST_PP_SEQ_FOR_EACH_PRODUCT 将进行迭代在两个或多个以(x) (y) (z)
形式编码的列表的笛卡尔积上(称为序列是库的说法).
BOOST_PP_SEQ_FOR_EACH_PRODUCT will iterate over the cartesian products of two or more lists encoded in the form (x) (y) (z)
(which are known as sequences is the library's parlance).
BOOST_PP_LIST_FOR_EACH_PRODUCT 可以编码为(x, (y, (z, NIL)))
的列表也是如此.
BOOST_PP_LIST_FOR_EACH_PRODUCT will do the same for lists encoded as (x, (y, (z, NIL)))
.
将 X宏迭代转换为这样的序列"很简单: /p>
It's trivial to convert the X macro iteration to a "sequence" like this:
#define LIST_TO_SEQ(X) (X)
ABC(LIST_TO_SEQ)
这篇关于使用C预处理程序的嵌套宏迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!