在地图中使用数据类型(类类型)作为键 [英] Use data type (class type) as key in a map
问题描述
我有类 Base
和类 Derived_1
, Derived_2
...
我需要派生类有一个id。这些id用于进一步查找等,因此需要是连续的(不仅仅是一些随机数)。因为派生类是由用户创建的,所以id不能是 Derived_N
的成员。所以我想出了 DerivedType
class。
class DerivedType
{
static unsigned id;
unsigned m_id;
public:
DerivedType():m_id(id ++){}
}
现在我想在 Derived_N
和 DerivedType
之间创建一个映射。
每当创建 Derived_N
时,此映射将查看 DerivedType
是否特定 Derived_N
已经存在并返回它,否则在地图中创建新的和存储。
实际问题:
有任何方法使用<在地图中使用数据类型作为键,将code> std :: map
我不怕任何模板元编程解决方案。
或者是否有优雅的方式如何实现我的目标?
编辑日期类型 - >数据类型,对不起:)
我想使用它:
Derived_5 d;
DerivedType dt = getType(d); // Derived_5在地图中查找,返回特定的DerivedType
dt.getId(); Derived_N
的每个实例
< N')应该有相同的id throu DerivedType
EDIT2 - 我的答案
我发现我的问题更好的解决方案...它是这样的:
atomic_counter s_nextEventClassID;
typedef int cid_t;
template< class EventClass>
class EventClassID
{
public:
static cid_t getID()
{
static cid_t classID = EventClassID :: next();
return classID;
}
static cid_t next(){return ++ s_nextEventClassID; }
};
因为我的问题是如何在地图中使用数据类型,我会标记一些你的答案,谢谢
$ <$> 您可以直接使用
typeid(object)
是 type_info :: before
,如果在地图中使用type_info作为键,可以用作比较器,请参阅什么是`type_info :: before`有用?无需获取 .name()
。 I have class Base
and classes Derived_1
, Derived_2
...
I need derived classes to have an id. Those ids are used for further lookups etc, and thus need to be consecutive (no just some random numbers). Because derived classes are created by user, id can not be member of Derived_N
. So I came up with DerivedType
class.
class DerivedType
{
static unsigned id;
unsigned m_id;
public:
DerivedType() : m_id(id++) { }
}
Now I want to create a mapping between Derived_N
and DerivedType
.
Whenever Derived_N
is created, this mapping looks if DerivedType
for particular Derived_N
already exist and returns it, otherwise create new and stores in the map.
Actual question:
Is there any way to use std::map
with data type as key in the map?
I am not afraid of any template-metaprogram solution.
Or is there elegant way how to achieve my goal?
edit Date type -> Data type, I mean like ClassType, I am sorry :)
I want to use it like:
Derived_5 d;
DerivedType dt = getType(d); //Derived_5 is looked up in map, returning particular DerivedType
dt.getId();
every instance of Derived_N
(with same 'N') should have the same id throu DerivedType
EDIT2 - MY ANSWER I found better solution for my problem... It is like this:
atomic_counter s_nextEventClassID;
typedef int cid_t;
template<class EventClass>
class EventClassID
{
public:
static cid_t getID()
{
static cid_t classID = EventClassID::next();
return classID;
}
static cid_t next() { return ++s_nextEventClassID; }
};
since my question was how to use datatype in a map, I will mark some of yours answers, thank you
You can use typeid(object)
directly, since there is type_info::before
, which can be used as comparator if you use type_info as key in the map, see What is `type_info::before` useful for?. No need to get .name()
.
这篇关于在地图中使用数据类型(类类型)作为键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!