我有类Base
和类Derived_1
,Derived_2
... 我需要派生类有一个id。这些ID用于进一步查找等,因此需要连续(不只是一些随机数)。因为派生类是由用户创建的,所以id不能是Derived_N
的成员。所以我想出了DerivedType
这个课。在地图中使用数据类型(类类型)作为键
class DerivedType
{
static unsigned id;
unsigned m_id;
public:
DerivedType() : m_id(id++) { }
}
现在我想创建Derived_N
和DerivedType
之间的映射。 每当创建Derived_N
时,此映射会查看DerivedType
是否已经存在,并返回它,否则创建新的并在地图中存储。
实际问题: 有没有办法使用std::map
与数据类型在地图上关键? 我不害怕任何模板元程序解决方案。 或者有没有优雅的方式来实现我的目标?
编辑日期类型 - >数据类型,我的意思是像类类别,不好意思:)
我想用它喜欢:
Derived_5 d;
DerivedType dt = getType(d); //Derived_5 is looked up in map, returning particular 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; }
};
,因为我的问题是,如何在地图中使用的数据类型,我将迎来一些你的答案,谢谢
这应该是被接受的答案 – jupp0r 2016-11-14 15:47:53
使用现代C++的很好的答案 – Anonymous 2017-06-14 10:32:43