可重复使用的预处理器__COUNTER__ [英] Reusable preprocessor __COUNTER__
问题描述
我正在做一些模板元编程,大多只是编写我自己的编译时间列表,但我也有一些预处理魔术,我想使用,以使事情更容易,如果可能的话。
I am doing some template meta programming, mostly just writing my own compile time list, but I also have some preprocessor magic which I want to use to make things easier if possible.
我要做的是创建一个编译时间列表的函子。这部分已经完成了,但是宏的缓存创建(并添加到列表)不是。
What I am trying to do is create a compile time list of functors. That part is done, but the macros to ease creation (and add to the list) are not.
简单的例子:
template<typename Functor, typename Tail>
struct node {
typedef Functor head;
typedef Tail tail;
};
template <typename Functor, typename Tail>
struct push_back {
typedef node<Functor, Tail> list;
};
struct unit0 {};
#define AUTO_FUNCTION(name) struct test_functor_##name { \
static void run_test(); \
}; \
typedef push_back< \
test_functor_##name, \
CONCAT(unit, PP_DEC(__COUNTER__)) \
>::list CONCAT(unit, __COUNTER__); \
void test_functor_##name::run_test()
AUTO_FUNCTION(hello) {
...
}
现在,这是因为我为PP_DEC创建了一组大的预处理器宏,即:
Now, this works because I have created a large set of preprocessor macros for PP_DEC, ie:
#define PP_DEC(x) PP_DEC_I(x)
#define PP_DEC_I(x) PP_DEC_ ## x
#define PP_DEC_1 0
#define PP_DEC_2 1
...
#define PP_DEC_N N
这是我真正想避免的部分,我提出这个问题的原因。是否有人建议我如何在不增加其值的情况下使用 COUNTER ,或者以其他方式完成类似的计数模式:
That's the part I really want to avoid and the reason I am asking this question. Does anyone have a suggestion on how I can use COUNTER without increasing its value, or some other way I can accomplish a counting pattern similar to:
0 1
1 2
2 3
...
建议改变push_back等的语义,当然也欢迎:)
Suggestions that change the semantics of push_back, etc. are of course also welcome :).
PS。这不是为了生产,只是为了乐趣。因此欢迎GCC具体扩展。
PS. This is not meant for production, only for fun. So GCC specific extensions are welcomed.
PPS。我试图避免外部依赖,例如boost,因为我想了解我在做的一切(这个项目的整个点)。
PPS. I am trying to avoid external dependencies, such as boost, as I want to understand everything I am doing (the whole point of this project).
推荐答案
您可以使用额外的宏来修复 __ COUNTER __
值:
#define MY_MACRO MY_MACRO_COUNTED(__COUNTER__)
#define MY_MACRO_COUNTED(counter) counter + counter
这篇关于可重复使用的预处理器__COUNTER__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!