SCC
SCC

Reputation: 720

Generating Unique ID's for Derived Classes

I am trying to write a base class, and a set of N derived classes, where each each derived class has its own unique identifier, here is a simple, 'manual' implementation:

struct Base {
    static int id_ = 0;
};

struct Derived1 : public Base {
    static int id_ = 1;
};

struct Derived2 : public Base {
    static int id_ = 2;
};

The problem is, if I want to continue adding derived classes, I must count the number of already existing derived classes.

Things also get more complicated, because I want to use a bitset to represent the unique ID. If every derived class's unique ID is basically just a different bit (of a common-length bitset) set to 1, it makes it very easy to perform binary AND/OR/XOR/etc operations on groups of derived classes.

The following is a incomplete and incorrect implementation of what I want

//Let DCOUNT be the number of derived classes, Ideally I shouldnt have to ever
//know/think about what it evaluates too, it should be automatic.
//But that is second priority, I would be willing to #define this to 
//some 'large' value, and not worry about it.
struct Base {
    static std::bitset<DCOUNT> id_ = generateUniqueID(); // "00000"
};

struct Derived1 {
    static std::bitset<DCOUNT> id_ = generateUniqueID(); // "00001"
};

struct Derived2 {
    static std::bitset<DCOUNT> id_ = generateUniqueID(); // "00010"
};

What is the best way to implement this? (or something like it)

Upvotes: 2

Views: 2592

Answers (2)

imreal
imreal

Reputation: 10368

What about something simple like a family of functions (template) that generates and keeps an id for each type, like this:

 template<typename T>
 static std::bitset<DCOUNT> getId()
 {
     static std::bitset<DCOUNT> bitset;
     static bool bitsetCreated = false;
     if ( false == bitsetCreated )
     {
        bitset = generateUniqueID();
        bitsetCreated = true;
     }
     return bitset;
 }

Afterwards you can get the IDs like this: getId < YourType > (); They are generated at runtime, so no problem with generateUniqueID();

Upvotes: 4

alestanis
alestanis

Reputation: 21863

This is RTTI.

You cannot initialize a static member with an external function, you will get compiler errors like

'generateUniqueID()' cannot appear in a constant-expression

or

ISO C++ forbids in-class initialization of non-const static member ‘id_’

I think that all you can do is initialize the id_ values by hand.

You also have an alternative to know the types of your classes: use the typeid function, as in

if (typeid(myInstance) == typeid(Derived1))
    do_something();

Upvotes: 0

Related Questions