【发布时间】:2012-03-25 10:17:56
【问题描述】:
我有课程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 时,此映射会查找特定 Derived_N 的 DerivedType 是否已存在并返回,否则创建新的并存储在映射中。
实际问题:
有没有办法在地图中将std::map 与data type 用作key?
我不怕任何模板元程序解决方案。
或者有没有优雅的方式来实现我的目标?
edit 日期类型 -> 数据类型,我的意思是像ClassType,对不起:)
我想像这样使用它:
Derived_5 d;
DerivedType dt = getType(d); //Derived_5 is looked up in map, returning particular DerivedType
dt.getId();
Derived_N 的每个实例(具有相同的“N”)都应该通过 DerivedType 具有相同的 id
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; }
};
因为我的问题是如何在地图中使用数据类型,所以我会标记你的一些答案,谢谢
【问题讨论】: