简体   繁体   English

在c ++中使用重复的宏

[英]using repeated macros in c++

assume i have a macro like this #define MY_MACRO(n) xxxxxxxxx // some code 假设我有一个这样的宏#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. 您可以使用boost的预处理器库或编写自己的库。 Good luck on the latter...it's frickin complicated. 祝后者好运......这太复杂了。 Preprocessor metaprogramming is tricky business. 预处理器元编程是一项棘手的业务。

Using boost preprocessor you would do something like so: 使用boost预处理器你可以这样做:

#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 ). 通过使用该循环, MY_MACRO(n)将被调用101次,其当前值为i0100 )。

Forget all the highly-educated teoreticians critics that just say NEVER-EVER-EVER dare to use macros! 忘记所有受过高等教育的teoreticians评论家,只是说从来没有 - 永远都敢使用宏!

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: 我所能建议的是,不是实际重复你的宏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)

Then you may do this: 然后你可以这样做:

MACRO_IX100(MYMACRO)

It's equivalent to invoking your macro 100 times with the appropriate expressions. 它相当于使用适当的表达式调用宏100次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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