Question

How to acces each element in macro if the definition is like MACRO(name, seq) and the code is like:

MACRO("TheName",
   (Elem1)
   (Elem2)
   (Elem3)
)

I want to generate the next code:

MACRO("TheName",
   ELEMMACRO(Elem1)
   ELEMMACRO(Elem2)
   ELEMMACRO(Elem3)
)

Or something like that. In other words, I want to process every parameter separately (I don't care of definition, even if it will be something like

MACRO("TheName",
   Elem1,
   Elem2,
   Elem3
)

There could be more elements, there could be less. I have tried __V_ARGS__ (I need it only for gcc), but I can only copy all the elements by that, not to process them separately.

What can I do?

P.S. Because of some reasons, I can't use Boost.

Was it helpful?

Solution

The easiest way is to use sequence iteration like this(it doesn't require boost):

#define PRIMITIVE_SEQ_ITERATE(...) __VA_ARGS__ ## _END
#define SEQ_ITERATE(...) PRIMITIVE_SEQ_ITERATE(__VA_ARGS__)

#define MACRO_EACH(seq) SEQ_ITERATE(MACRO_EACH_1 seq) 
#define MACRO_EACH_1(...) ELEMMACRO(__VA_ARGS__) MACRO_EACH_2
#define MACRO_EACH_2(...) ELEMMACRO(__VA_ARGS__) MACRO_EACH_1
#define MACRO_EACH_1_END
#define MACRO_EACH_2_END

Which will call your ELEMMACRO for each element in the sequence:

MACRO_EACH
(
    (Elem1)
    (Elem2)
    (Elem3)
)

And will expand to this:

ELEMMACRO(Elem1)
ELEMMACRO(Elem2)
ELEMMACRO(Elem3)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top