使用偏移量获取宏值的子集 [英] Get subsets of macro values using offset
问题描述
我有一个列表定义为预处理器值#define LIST 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
.我想编写一个获取索引0或1并计算为LIST
子集的宏,这样对于索引0它将评估为0, 2, 4, 6, 8
,对于索引1它将评估为1, 3, 5, 7, 9
.可以保证LIST
的长度是偶数,但我事先不知道内容(它是由我提供的库的用户自动生成的).此问题是对此问题
I have a list defined as a preprocessor value #define LIST 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
. I want to write a macro that gets an index 0 or 1 and evaluates to a subset of the LIST
such that for index 0 it will evaluate to 0, 2, 4, 6, 8
and for index 1 it will evaluate to 1, 3, 5, 7, 9
. It is guaranteed that LIST
's length is even but I don't know the content in advance (it is auto generated by the users of the library I supply). This question is a follow up on this question
#define LIST 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
#define MACRO(index) \
use LIST and index
// For LIST that given in the example
printf("%d %d %d %d %d\n", MACRO(0)); // print 0 2 4 6 8
printf("%d %d %d %d %d\n", MACRO(1)); // print 1 3 5 7 9
推荐答案
在 [实时示例]
通过将LIST
转换为Boost.Preprocessor sequence ,然后对其进行迭代并仅保留索引模2与MACRO
的index
参数匹配的那些元素,最后进行工作将生成的序列转回以逗号分隔的列表.
It works by turning LIST
into a Boost.Preprocessor sequence, then iterating over it and keeping only those elements whose index modulo 2 matches the index
parameter of MACRO
, and finally turning the resulting sequence back into a comma-separated list.
请注意,Boost.Preprocessor元组的最大大小是有限制的.在版本1.66.0(撰写本文时为最新版本)中,它是64.如果您的LIST
较大,则不能将其视为元组(上面的代码通过使用(LIST)
将一对括号括起来)它).
Note that there is a limit on the maximum size of a Boost.Preprocessor tuple. In version 1.66.0 (the latest as of this writing), it's 64. If your LIST
is larger, it cannot be treated as a tuple (which the code above does by using (LIST)
to put a pair of parentheses around it).
如果您可以控制LIST
的格式,则可以直接将其更改为Boost.Preprocessor序列:
If you have control over the format of LIST
, you could change it do be a Boost.Preprocessor sequence directly:
#define LIST (0)(1)(2)(3)(4)(5)(6)(7)(8)(9)
虽然序列也有大小限制,但它要大得多(Boost 1.66.0中为256).然后,宏将更改如下:
While sequences have a size limit too, it's far larger (256 in Boost 1.66.0). The macro would then change as follows:
#define MACRO(index) \
BOOST_PP_SEQ_ENUM( \
BOOST_PP_SEQ_FOR_EACH_I( \
OUTPUT_CORRECT_OFFSET, \
index, \
LIST \
) \
)
如果序列限制仍然不够,您将不得不考虑使用更强大的代码生成技术,例如本机C ++框架之外的独立宏处理器.
If the sequence limit is still not enough, you will have to consider a more powerful code generation technique, such as a stand-alone macro processor outside the native C++ framework.
这篇关于使用偏移量获取宏值的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!