基于宏的计数器 [英] Macro-based counter

查看:88
本文介绍了基于宏的计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建像这样的编译时间常数:

 //event.h#define REGISTER_EVENT_TYPE()...//返回last_returned_number + 1//标头1#定义SOME_EVENT REGISTER_EVENT_TYPE()//标头2#定义SOME_OTHER_EVENT REGISTER_EVENT_TYPE() 

其中 SOME_EVENT 将为0, SOME_OTHER_EVENT 将为1.

尝试以下代码:

  #define DEF_X(x)const int x = BOOST_PP_COUNTER;#定义REGISTER_EVENT_TYPE(x)BOOST_PP_UPDATE_COUNTER()DEF_X(x)#include REGISTER_EVENT_TYPE(SOME_EVENT_TYPE) 

但是include吃的是常量声明.

解决方案

可以,但是可以使用 const/constexpr int 和Boost.Preprocessor.

请参见 BOOST_PP_COUNTER

用法示例:

  #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 

请参见工作示例.


最后的提示:不要使用宏来存储结果,最后在所有这样定义的常量中将得到相同的数字:

  #include< boost/preprocessor/slot/counter.hpp>#define A BOOST_PP_COUNTER//A为0#include BOOST_PP_UPDATE_COUNTER()#define B BOOST_PP_COUNTER//B为1,但A也为1int main(){cout<<A<<B<<恩德尔} 

输出:

  11 

Is it possible to create compile time constants like this:

// event.h
#define REGISTER_EVENT_TYPE() ... // Returns last_returned_number+1

// header1
#define SOME_EVENT REGISTER_EVENT_TYPE()
// header2
#define SOME_OTHER_EVENT REGISTER_EVENT_TYPE()

Where SOME_EVENT will be 0 and SOME_OTHER_EVENT will be 1.

Tried the following code:

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

But include eats constant declaration.

解决方案

Yes, it is possible, but with const/constexpr int and with Boost.Preprocessor.

See BOOST_PP_COUNTER

An example of usage:

#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

See working example.


Final note: don't use macro for storing results, you'll get the same number in the end in all such defined constants:

#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; }

Output:

 11

这篇关于基于宏的计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆