生成类唯一ID的有效方法? [英] Efficient way to generate id unique to class?

查看:79
本文介绍了生成类唯一ID的有效方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,是否有任何有效的方法来生成类(而不是实例)唯一的ID?我正在寻找这种简单程度的东西(这会为每个实例而不是每个类类型生成一个ID):

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++;
}

编辑:为什么我想要唯一的ID。

Why I want unique IDs.

我正在写游戏。我游戏中的所有实体都会处于不同的状态(向左行走,跳跃,站立等);这些状态在类中定义。每个州都需要有自己的ID,以便我可以识别它。

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;
}

然后只需使用:

get_id<int>(); // etc.

当然,这不是线程安全的。

Of course, this isn't thread safe.

同样,它不是确定性的:ID是在您第一次为每种类型调用函数时生成的。因此,如果在一次运行中您在 get_id< float>()之前调用 get_id< int>()如果您以相反的方式调用它们,那么它们将具有不同的ID。但是,它们一次运行对每种类型来说都是唯一的。

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.

这篇关于生成类唯一ID的有效方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆