Is it possible to define a C/C++ macro “BUILD(a, i)” which expands to “x[0], x[1], x[2], ..., x[i]” ? Like in
#define BUILD(x, 0) x[0]
#define BUILD(x, 1) x[0], x[1]
#define BUILD(x, 2) x[0], x[1], x[2]
...
It seems BOOST_PP_ENUM_PARAMS could do the job. I suppose I could just #include boost, but I’m interested in knowing how and why it works, anyone can explain?
I would like to call a function f(int, ...) which takes N int arguments x[i], 0 <= i < N. Where N is known to be ceil(sizeof(A) / sizeof(B)). So unfortunately, I cannot use varargs or templates.
It is possible, but you have to do some manual work and have an upper limit.
And note that
ishould be an integer literal, not a constant computed value.BTW, the preprocessor is more powerful than what is usually though, but the use of that power is quite tricky. Boost provides a library which eases some things, including iteration. See Boost Preprocessor Library. There is another library for such things, but its name escapes me at the moment.
Edit: The boost preprocessor library uses a similar technique. With additional tricks to solve some corner cases problems, share implementation macros between higher level facilities, work around compiler bugs, etc… the usual boost complexity which is normal in the context of a general purpose library but which at times prevents easy understanding of the implementation principles. Probably the most noticeable trick is to add an indirection level so that if the second parameter can be a macro, it is expanded. I.e. with
one can make the call
which isn’t possible with what I exposed.