简体   繁体   中英

using repeated macros in c++

assume i have a macro like this #define MY_MACRO(n) xxxxxxxxx // some code

then I want to use it many times like

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

is there a better way of doing this? (I have to use macros)

You can use iteration. You can use boost's preprocessor library or write your own. Good luck on the latter...it's frickin complicated. Preprocessor metaprogramming is tricky business.

Using boost preprocessor you would do something like so:

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

BOOST_PP_REPEAT(101, MY_MACRO_N, ~)

You can do something like this:

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

By using this loop MY_MACRO(n) whould be called 101 times with the current value of i ( 0 to 100 ).

Forget all the highly-educated teoreticians critics that just say NEVER-EVER-EVER dare to use macros!

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

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

Now regarding your question. If your macro evaluates to an expression where its parameter may be a run-time parameter - you may use a loop.

If your macro demands a compile-time known constant - you may consider using templates (if applicable).

If your macro demands an expression which is a numerical constant - there are no alternatives left.

All I can suggest is instead of actually repeating your macro 100 times you may do some tricks, such as the following:

#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)

Then you may do this:

MACRO_IX100(MYMACRO)

It's equivalent to invoking your macro 100 times with the appropriate expressions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM