Use Boost Preprocessor to Parse sequence of elements
Asked Answered
K

1

4

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.

Kath answered 29/9, 2016 at 9:9 Comment(0)
U
7

Using BOOST_PP_VARIADIC_SEQ_TO_SEQ 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 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, ~, BOOST_PP_VARIADIC_SEQ_TO_SEQ(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

Unhinge answered 29/9, 2016 at 9:43 Comment(5)
Shouldn't boost already have something like that GLK_PP_SEQ_DOUBLE_PARENS?Runck
@Phantom not that I know of, unfortunately.Unhinge
@Quentin, check out BOOST_PP_VARIADIC_SEQ_TO_SEQ. (boost.org/doc/libs/1_71_0/libs/preprocessor/doc/ref/…)Hell
@Quentin, if there are commas between (height, int, 10) and (width, int, 20) , Can you explain what to do to parse sequence?Ecclesiastes
@JafarGh this can be done by replacing BOOST_PP_VARIADIC_SEQ_TO_SEQ with BOOST_PP_TUPLE_TO_SEQ, give or take a few parentheses: live demo.Unhinge

© 2022 - 2024 — McMap. All rights reserved.