DejaVu
DejaVu

Reputation: 155

Macro-based counter

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.

Upvotes: 1

Views: 1196

Answers (1)

PiotrNycz
PiotrNycz

Reputation: 24422

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

Upvotes: 1

Related Questions