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.

bhawesh
  • 1,220
  • 2
  • 18
  • 55

1 Answers1

5

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

Quentin
  • 58,778
  • 7
  • 120
  • 175
  • Shouldn't boost already have something like that GLK_PP_SEQ_DOUBLE_PARENS? – Gam Oct 06 '17 at 21:40
  • @Phantom not that I know of, unfortunately. – Quentin Oct 07 '17 at 08:41
  • @Quentin, check out BOOST_PP_VARIADIC_SEQ_TO_SEQ. (https://www.boost.org/doc/libs/1_71_0/libs/preprocessor/doc/ref/variadic_seq_to_seq.html) – Lance E.T. Compte Nov 02 '19 at 04:23
  • @Quentin, if there are commas between `(height, int, 10)` and `(width, int, 20)` , Can you explain what to do to parse sequence? – Jafar Gh Apr 02 '20 at 12:48
  • 1
    @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](http://coliru.stacked-crooked.com/a/b34717ecbf6ba634). – Quentin Apr 02 '20 at 17:18