Macro-based counter

倖福魔咒の 提交于 2021-02-19 07:43:26

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/28724307/macro-based-counter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!