【问题标题】:How to iterate over two Boost Preprocessor sequences at the same time?如何同时迭代两个 Boost Preprocessor 序列?
【发布时间】:2017-06-18 09:04:02
【问题描述】:

我想知道是否可以通过 Boost Preprocessor 序列完成以下操作。 (大多数 SO 问题以及 Boost Preprocessor 示例只讨论 1 个序列)

#define seq1 (a)(b)(c)
#define seq2 (1)(2)(3)

// Now iterate over both of them at the same time

这是我的动机。我必须为很多类型定义几个函数,例如

void add(int val) { obj.AddInt(val); }
void add(double val) { obj.AddDouble(val); }

我正在考虑定义两个序列,例如

#define types (int)(double)...
#define funcs (AddInt)(AddDouble)...

然后为函数add写一个宏,遍历这两个序列。

【问题讨论】:

  • 为什么不是一个元组序列?例如。 ((int, AddInt), (double, AddDouble))...
  • 我实际上有 3-4 个序列,我已经阅读了这个问题:stackoverflow.com/questions/26475453/… 我想这可能可以做到,但想知道是否有一种方法可以迭代多个序列,因为这些宏序列已经定义了。
  • 快速搜索显示有一个带有 zip 宏的库:github.com/mcinglis/libpp/blob/master/zip.h

标签: c++ c boost c-preprocessor boost-preprocessor


【解决方案1】:

您可以使用BOOST_PP_SEQ_FOR_EACH_I 和BOOST_PP_SEQ_ELEM 进行如下操作:

#include <boost/preprocessor/seq/elem.hpp>
#include <boost/preprocessor/seq/for_each_i.hpp>

#define types (int)(double)
#define funcs (AddInt)(AddDouble)

#define MACRO(_,funcs,i,type) \
    void add(type val) { obj.BOOST_PP_SEQ_ELEM(i, funcs)(val); }

BOOST_PP_SEQ_FOR_EACH_I(MACRO, funcs, types)

BOOST_PP_SEQ_FOR_EACH_I 宏迭代序列types,将MACRO 应用于每个元素。 BOOST_PP_SEQ_FOR_EACH_I 的第二个参数作为第二个参数传递给MACRO 的每个调用,i 表示被迭代的当前元素的从零开始的索引。因此,当MACRO被扩展时,type是types的i-th元素,BOOST_PP_SEQ_ELEM(i, funcs)是funcs的i-th元素。

对于更通用的解决方案,您可以执行以下操作:

#define ITERATE_OVER_TWO_SEQ_(_,data,i,e2) \
   BOOST_PP_SEQ_ELEM(0,data)(BOOST_PP_SEQ_ELEM(i, BOOST_PP_SEQ_ELEM(1,data)), e2)
#define ITERATE_OVER_TWO_SEQ(macro, s1, s2) \
    BOOST_PP_SEQ_FOR_EACH_I(ITERATE_OVER_TWO_SEQ_, (macro)(s1), s2)

并按如下方式使用:

#define MACRO(type,func) void add(type val) { obj.func(val); }
ITERATE_OVER_TWO_SEQ(MACRO, types, funcs)

更通用的方法是使用this answer、BOOST_PP_SEQ_FOR_EACH 和BOOST_PP_SEQ_ELEM 中的SEQ_ZIP。例如:

#include <boost/preprocessor/seq/for_each.hpp>
#define MACRO(_,d,seq) \
    void add(BOOST_PP_SEQ_ELEM(0,seq) val) \
    { obj.BOOST_PP_SEQ_ELEM(1, seq)(val); }

BOOST_PP_SEQ_FOR_EACH(MACRO, _, SEQ_ZIP((types)(funcs))

【讨论】:

    猜你喜欢
    • 2015-01-23
    • 2010-11-11
    • 2014-12-16
    • 2016-08-02
    • 2023-01-12
    • 1970-01-01
    • 2017-02-07
    • 2014-02-01
    • 1970-01-01
    相关资源
    最近更新 更多