Macro-based counter
Asked Answered
C

1

1

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.

Cinderella answered 25/2, 2015 at 16:28 Comment(3)
You want a macro that returns a different constant every time it is "called"? I'm pretty sure that is not possible.Applicative
Macros is compile-time, and you are asking for data in execution time... It can't be posible.Monachism
Similar question and possible answer using enum: https://mcmap.net/q/703723/-can-you-make-an-incrementing-compiler-constantMajorette
G
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
Grassofparnassus answered 25/2, 2015 at 17:2 Comment(3)
Thanks, but I know about BOOST_PP_COUNTER, and I am trying to find a way to wrap following code to single macro. constexpr int A = BOOST_PP_COUNTER; #include BOOST_PP_UPDATE_COUNTER()Cinderella
@Cinderella - please remember to always add or at least mention what have you tried so far. Anyway: I leave this answer. I hope it serves for others.Grassofparnassus
@Cinderella - answering on your question in comment: Well - you cannot have # in macro definition. I am afraid you need two lines of code for new ID, or, why don't you just use enum...Grassofparnassus

© 2022 - 2024 — McMap. All rights reserved.