开发者

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::M开发者_如何学GoyClass()
{
    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.


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.


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


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.]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜