jtedit
jtedit

Reputation: 1470

Enum over multiple files, or automatic unique constants over multiple files

In C++ is there any way to automatically generate constants over multiple files at compile time? Just like how an enum has constants automatically generated in a single file, but the constants must be unique over multiple files.

Eg:

classBase.hpp

classBase{
    //blah blah
};

classA.hpp

class childA : public classBase{
private:
    static const unsigned int mID = NEXT_ID;    
};

classB.hpp

class childB : public classBase{
private:
    static const unsigned int mID = NEXT_ID;    
};

classC.hpp

class childC : public classBase{
private:
    static const unsigned int mID = NEXT_ID;    
};

So in this case, each class inheriting from classBase would automatically be assigned the next ID (0, 1, 2...)

I would guess there is a way to do it with #define s, but I don't know of any way to automatically increment a #define each time something is assigned to it, is there a way to do this?

Upvotes: 1

Views: 293

Answers (1)

Adriano Repetti
Adriano Repetti

Reputation: 67118

It's not easy to generate a sequence at compile time by your own but most compilers supports a macro for this purpose: __COUNTER__. It's a counter, increased by the compiler itself each time it's used in source code so you can use it across multiple files. For example your code could be:

class childB : public classBase {
private:
    static const unsigned int mID = __COUNTER__;    
};

If your compiler doesn't provide that macro (or you need more control over IDs generation) then you have to write much more code but it can be done with template metaprogramming.

Upvotes: 4

Related Questions