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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
DejaVu
  • 155
  • 10

1 Answers1

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
PiotrNycz
  • 23,099
  • 7
  • 66
  • 112
  • 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()` – DejaVu Feb 25 '15 at 17:07
  • @DejaVu - 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. – PiotrNycz Feb 25 '15 at 17:43
  • 1
    @DejaVu - 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`... – PiotrNycz Feb 25 '15 at 17:46