可重用预处理器 __COUNTER__
我正在做一些模板元编程,主要是编写我自己的编译时间列表,但我也有一些预处理器魔法,我想用它们来使事情变得更容易(如果可能的话)。
我想做的是创建一个函子的编译时列表。该部分已完成,但用于简化创建(并添加到列表中)的宏尚未完成。
一个简单的例子:
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 创建了一大堆预处理器宏,即:
#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 而不增加其值有任何建议,或者我可以通过其他方式完成类似于以下内容的计数模式:
0 1
1 2
2 3
...
更改 push_back 等语义的建议当然也是欢迎 :)。
附言。这不是为了生产,只是为了娱乐。因此,欢迎 GCC 特定扩展。
聚苯硫醚。我试图避免外部依赖,例如 boost,因为我想了解我正在做的一切(这个项目的全部意义)。
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.
An example in brief:
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) {
...
}
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
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
...
Suggestions that change the semantics of push_back, etc. are of course also welcome :).
PS. This is not meant for production, only for fun. So GCC specific extensions are welcomed.
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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用额外的宏来“修复”
__COUNTER__
值:You can "fix"
__COUNTER__
value by using an extra macro: