简体   繁体   中英

Integer values in compile time

I have to write some constants in different files with some integer id. For example:

#define MESSAGE_FIRST 0

In other file:

#define MESSAGE_ANOTHER 1

Any ways to get that id automatically in compile time? Something like:

#define MESSAGE_AUTO GetNextId()

I can't use enums here because this directives will be in different files.

Thanks.

ps GCC, Linux

You can do a compile-time counter, with inheritance and function overloading:

template<unsigned int n> struct Count { bool data[n]; };
template<int n> struct Counter : public Counter<n-1> {};
template<> struct Counter<0> {};
Count<1> GetCount(Counter<1>);

#define MAX_COUNTER_NUM 64
#define COUNTER_VALUE (sizeof(GetCount(Counter<MAX_COUNTER_NUM + 1>())) / sizeof(bool))
#define INC_COUNTER Count<COUNTER_VALUE + 1> GetCount(Counter<COUNTER_VALUE + 1>);

You can see it in action here . Also works with msvc.

You say you are using GCC. GCC has the (AFAIK per-file) macro called __COUNTER__ that increments by one after every use.

Note that this is an extension and not included in standard C++.

Another option is using an enum:

enum {
    FIRST = 0,
    SECOND,
    THIRD
};

Or you can do this manually using preprocessor directives like this:

#define FIRST 0
#define SECOND (1 + FIRST)
#define THIRD (1 + SECOND)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM