Using repeating macros in C ++

Suppose I have such a macro #define MY_MACRO(n) xxxxxxxxx // some code

then I want to use it many times, for example

MY_MACRO(0)
MY_MACRO(1)
MY_MACRO(2)
MY_MACRO(3)
...
MY_MACRO(100)

Is there a better way to do this? (I have to use macros)

+3
source share
3 answers

Forget all critics of highly educated theorists who just say NEVER, NEVER dare to use macros!

Macros are indeed a necessary evil. Yes, sometimes there are other options, such as templates, polymorphism, and other things. But it is not always possible to get rid of repetitions without the use of macros.

And, in my humble opinion, macros are a better alternative than rewriting the same endless time.

. , , .

, ( ).

, , .

, , , 100 , , :

#define MACRO_IX10(m, i) \
    m(i##0) \
    m(i##1) \
    m(i##2) \
    m(i##3) \
    m(i##4) \
    m(i##5) \
    m(i##6) \
    m(i##7) \
    m(i##8) \
    m(i##9)

#define MACRO_IX100(m) \
    MACRO_IX10(m, ) \
    MACRO_IX10(m, 1) \
    MACRO_IX10(m, 2) \
    MACRO_IX10(m, 3) \
    MACRO_IX10(m, 4) \
    MACRO_IX10(m, 5) \
    MACRO_IX10(m, 6) \
    MACRO_IX10(m, 7) \
    MACRO_IX10(m, 8) \
    MACRO_IX10(m, 9)

:

MACRO_IX100(MYMACRO)

100 .

0

. boost . ... . - .

boost, - :

#define MY_MACRO_N(Z,N,D) MY_MACRO(N)

BOOST_PP_REPEAT(101, MY_MACRO_N, ~)
+6

You can do something like this:

int i;
for (i = 0; i <= 100; i++)
    MY_MACRO(i);

Using this loop MY_MACRO(n), it will be called 101 times with the current value i( 0before 100).

+1
source

All Articles