Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A macro for expanding an arbitrary macro a certain number of times?

I want to write the C macros which takes either an integer literal or something akin to an integer literal, and the name of another macro, and expands that other macro as many times as the value of the integer literal, with the index as an argument, e.g.

MAGIC(4, FUN)

expands to

FUN(0) FUN(1) FUN(2) FUN(3)

If, instead, I would have MORE_MAGIC which takes a range start and length, that would be even nicer:

e.g.

MORE_MAGIC(1, 3, FUN)

expands to

FUN(1) FUN(2) FUN(3)

Note:

  • I can live with the number of expansions being limited to, I dunno, 99, or 50, or something like that.
  • You cannot make assumptions regarding FUN. The needs to be generic. And no, this is not for manually unrolling for loops.
  • C-only solutions are the most welcome as well as solutions which require C++ (e.g. if you somehow use templates in your solution).
  • The total number of lines of a solution (including #include's but excluding comments) should preferably be modest. Say, no more than 200.
like image 655
einpoklum Avatar asked Oct 28 '25 04:10

einpoklum


1 Answers

Boost Preprocessor is an extensive library, focusing on such pre-processor magic.

It offers a macro called BOOST_PP_REPEAT_FROM_TO, which does exactly what you want.

Full reference is available here:
http://boost.org/libs/preprocessor

like image 143
zah Avatar answered Oct 29 '25 19:10

zah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!