phaazon
phaazon

Reputation: 2002

Metaprogramming via macro

I’d like to do the same stuff we can do with D’s mixins with C/C++ preprocessor. I’d like to write a function to generate a parameter list. For instance:

#define MK_FN_FOO(n,t) …

MK_FN_FOO(3,float)

/* it will expand into */
void foo(float x0, float x1, float x2) {
    /* do something else here */
}

I have some idea but I’m facing an issue. I have to do recursion and I have no idea how I could do such a thing:

#define MK_FOO(n,t) void foo(MK_FOO_PLIST(n-1,t)) { }
#define MK_FOO_PLIST(n,t) t xn, MK_FOO_PLIST(n-1,t) /* how stop that?! */

Upvotes: 2

Views: 150

Answers (2)

huysentruitw
huysentruitw

Reputation: 28091

I've checked out the boost implementation in /boost/preprocessor/repetition/repeat.hpp and for your example it would boil down to something like this:

#define MK_FN_FOO_REPEAT_0(t)
#define MK_FN_FOO_REPEAT_1(t) MK_FN_FOO_REPEAT_0(t)  t x0
#define MK_FN_FOO_REPEAT_2(t) MK_FN_FOO_REPEAT_1(t), t x1
#define MK_FN_FOO_REPEAT_3(t) MK_FN_FOO_REPEAT_2(t), t x2
#define MK_FN_FOO_REPEAT_4(t) MK_FN_FOO_REPEAT_3(t), t x3
// etc... boost does this up to 256

#define MK_FN_FOO(n, t) void foo(MK_FN_FOO_REPEAT_ ## n(t))

MK_FN_FOO(3, float) // will generate: void foo(float x0, float x1, float x2)
{
}

Upvotes: 0

Salgar
Salgar

Reputation: 7775

The boost libraries have a vast extensive metaprogramming and everything else preprocessor library. It is possible to do this kind of thing using their utility preprocessor directives which will be much easier than doing it yourself, although still slightly confusing :)

I suggest you start there:

http://www.boost.org/doc/libs/1_53_0/libs/preprocessor/doc/index.html

http://www.boost.org/doc/libs/?view=category_Preprocessor

Edit: Here is another tutorial about them: Boost.Preprocessor - Tutorial

Upvotes: 4

Related Questions