Search code examples
c++cc-preprocessorboost-preprocessor

How to zip multiple Boost Preprocessor sequences?


Given multiple Boost Preprocessor sequences:

#define S1 (a)(b)(c)
#define S2 (1)(2)(3)
#define S3 (x1)(x2)(x3)

How do I zip them using the preprocessor so the end result would be ((a)(1)(x1))((b)(2)(x2))((c)(3)(x3))?


Solution

  • You can define a SEQ_ZIP macro for this purpose as follows:

    #include <boost/preprocessor/control/expr_if.hpp>
    #include <boost/preprocessor/repetition/repeat.hpp>
    #include <boost/preprocessor/seq/elem.hpp>
    #include <boost/preprocessor/seq/for_each.hpp>
    #include <boost/preprocessor/seq/size.hpp>
    
    #define SEQ_ZIP_NTH_(_,d,e) (BOOST_PP_SEQ_ELEM(d, e))
    #define SEQ_ZIP_NTHS_(_,i,ss) (BOOST_PP_SEQ_FOR_EACH(SEQ_ZIP_NTH_,i,ss))
    #define SEQ_ZIP_2(ne,ss) BOOST_PP_REPEAT(ne, SEQ_ZIP_NTHS_, ss)
    #define SEQ_ZIP_(ne,ss) BOOST_PP_EXPR_IF(ne, SEQ_ZIP_2(ne, ss))
    #define SEQ_ZIP(ss) SEQ_ZIP_(BOOST_PP_SEQ_SIZE(BOOST_PP_SEQ_ELEM(0,ss)), ss)
    

    And use it to zip your sequences like this:

    #define S1 (a)(b)(c)
    #define S2 (1)(2)(3)
    #define S3 (x1)(x2)(x3)
    SEQ_ZIP((S1)(S2)(S3))