Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to generate id unique to class?

Is there any efficient way in C++ of generating an ID unique to the class, not to the instance? I'm looking for something of this level of simplicity (this generates an ID for every instance, not for every class type):

MyClass::MyClass()
{
    static unsigned int i = 0;
    id_ = i++;
}

Edit: Why I want unique IDs.

I'm writing a game. All entities in my game will have different states they can be in (walking left, jumping, standing, etc); these states are defined in classes. Each state needs to have its own ID so I can identify it.

like image 679
Paul Manta Avatar asked Jun 15 '11 22:06

Paul Manta


3 Answers

You can try this, but it's not-deterministic.

int id_count = 0;

template <typename T>
int get_id()
{
    static int id = id_count++;
    return id;
}

Then just use:

get_id<int>(); // etc.

Of course, this isn't thread safe.

Again, it's not deterministic: the IDs are generated the first time you call the function for each type. So, if on one run you call get_id<int>() before get_id<float>() then on another run you call them the other way round then they'll have different IDs. However, they will always be unique for each type in a single run.

like image 58
Peter Alexander Avatar answered Oct 23 '22 13:10

Peter Alexander


Basically you are asking for a custom rolled RTTI solution, that you can selectively apply to classes.

This can start from very crude preprocessor stuff like :

#define DECLARE_RTTI_CLASS(a) class a {  \
     inline const char * class_id() { return #a };

.. to a more sophisticated solutions that track inheritance etc, essentially partially duplicating compiler RTTI functionality. For an example, see Game Programming Gems #2, Dynamic Type Information

Previous discussions on gamedev on the same subject are also worth reading

like image 4
kert Avatar answered Oct 23 '22 13:10

kert


Use your MyClass as a primitive, and incorporate a static instance of one into each class you want to ID.

class MyOtherClass1 {
    static MyClass id;
};

class MyOtherClass2 {
    static MyClass id;
};

[etc.]
like image 1
Nemo Avatar answered Oct 23 '22 14:10

Nemo