Macro-based counter
是否可以像这样创建编译时常量:
|
1
2 3 4 5 6 7 |
// event.h
#define REGISTER_EVENT_TYPE() … // Returns last_returned_number+1 // header1 |
其中 SOME_EVENT 为 0,SOME_OTHER_EVENT 为 1。
尝试了以下代码:
|
1
2 3 4 |
#define DEF_X(x) const int x = BOOST_PP_COUNTER;
#define REGISTER_EVENT_TYPE(x) BOOST_PP_UPDATE_COUNTER()DEF_X(x) #include REGISTER_EVENT_TYPE(SOME_EVENT_TYPE) |
但是包含吃常量声明。
- 您想要一个每次”调用”时都返回不同常量的宏吗?我很确定这是不可能的。
- 宏是编译时的,而您在执行时要求数据……这是不可能的。
是的,这是可能的,但是使用 const/constexpr int 和 Boost.Preprocessor。
见 BOOST_PP_COUNTER
使用示例:
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <boost/preprocessor/slot/counter.hpp>
constexpr int A = BOOST_PP_COUNTER; // 0 #include BOOST_PP_UPDATE_COUNTER() constexpr int B = BOOST_PP_COUNTER; // 1 #include BOOST_PP_UPDATE_COUNTER() constexpr int C = BOOST_PP_COUNTER; // 2 #include BOOST_PP_UPDATE_COUNTER() constexpr int D = BOOST_PP_COUNTER; // 3 |
参见工作示例。
最后注意:不要使用宏来存储结果,你会在所有这些定义的常量中得到相同的数字:
|
1
2 3 4 5 6 7 8 9 |
#include <boost/preprocessor/slot/counter.hpp>
#define A BOOST_PP_COUNTER // A is 0 #include BOOST_PP_UPDATE_COUNTER() #define B BOOST_PP_COUNTER // B is 1, but A is 1 too int main() { cout << A << B << endl; } |
输出:
|
1
|
11
|
- 谢谢,但我知道 BOOST_PP_COUNTER,我正在尝试找到一种方法将以下代码package到单个宏中。 constexpr int A = BOOST_PP_COUNTER; #include BOOST_PP_UPDATE_COUNTER()
- @DejaVu – 请记住始终添加或至少提及您迄今为止尝试过的内容。无论如何:我留下这个答案。我希望它为其他人服务。
- @DejaVu – 在评论中回答你的问题:嗯 – 你不能在宏定义中有 # 。恐怕您需要两行代码来获取新 ID,或者,您为什么不直接使用 enum…
来源:https://www.codenong.com/28724307/
