bhawesh bhawesh - 2 months ago 21
C++ Question

Use Boost Preprocessor to Parse sequence of elements

I have a macro defined which is

#define TYPES (height,int,10)(width,int,20)


How to expand this macro using Boost Preprocessor something like this?

int height = 10;
int width = 20;


at most i am able to get is height,int,10 and width,int,20 as string but can't parse individual element.

Answer

Using a pinch of custom macros to turn TYPES into ((height,int,10))((width,int,20)) before processing, so that BOOST_PP_SEQ_FOR_EACH doesn't choke on it:

#define GLK_PP_DETAIL_SEQ_DOUBLE_PARENS_0(...) \
     ((__VA_ARGS__)) GLK_PP_DETAIL_SEQ_DOUBLE_PARENS_1

#define GLK_PP_DETAIL_SEQ_DOUBLE_PARENS_1(...) \
     ((__VA_ARGS__)) GLK_PP_DETAIL_SEQ_DOUBLE_PARENS_0

#define GLK_PP_DETAIL_SEQ_DOUBLE_PARENS_0_END
#define GLK_PP_DETAIL_SEQ_DOUBLE_PARENS_1_END

// Double the parentheses of a Boost.PP sequence
// I.e. (a, b)(c, d) becomes ((a, b))((c, d))
#define GLK_PP_SEQ_DOUBLE_PARENS(seq) \
    BOOST_PP_CAT(GLK_PP_DETAIL_SEQ_DOUBLE_PARENS_0 seq, _END)


#define MAKE_ONE_VARIABLE(r, data, elem) \
    BOOST_PP_TUPLE_ELEM(1, elem) BOOST_PP_TUPLE_ELEM(0, elem) = BOOST_PP_TUPLE_ELEM(2, elem);

#define MAKE_VARIABLES(seq) \
    BOOST_PP_SEQ_FOR_EACH(MAKE_ONE_VARIABLE, ~, GLK_PP_SEQ_DOUBLE_PARENS(seq))

Usage:

#define TYPES (height,int,10)(width,int,20)

int main() {
    MAKE_VARIABLES(TYPES)
}

Is preprocessed into:

int main() {
    int height = 10; int width = 20;
}

See it live on Coliru