通过宏进行元编程

Metaprogramming via macro

本文关键字:编程      更新时间:2023-10-16

我想做同样的事情,我们可以用C/c++预处理器做D的mixins。我想写一个函数来生成一个参数表。例如:

#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 */
}

我有一些想法,但我面临一个问题。我必须做递归,我不知道怎么做这样的事情:

#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?! */

boost库具有大量的元编程和其他所有预处理器库。可以使用他们的实用程序预处理器指令来做这种事情,这比自己做要容易得多,尽管仍然有点令人困惑:)

我建议你从这里开始:

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

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

编辑:这里是另一个关于它们的教程:提振。预处理器-教程

我已经检查了/boost/preprocessor/repetition/repeat.hpp中的boost实现,对于您的示例,它将归结为这样的内容:

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