我有类 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
是否已经存在并返回,否则创建新的并存储在映射中。
实际问题:
有没有办法在 map 中使用 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; }
};
因为我的问题是如何在 map 中使用数据类型,所以我会标记你的一些答案,谢谢
最佳答案
C++11 通过提供 std::type_index
解决了这个问题。 , 在 <typeindex>
,它是由 std::type_info
构造的可复制、可比较和可散列的对象可用作关联容器中的键的对象。
(实现相当简单,因此即使您自己没有 C++11,您也可以从 GCC 4.7 中窃取实现,然后在您自己的代码中使用它。)
#include <typeindex>
#include <typeinfo>
#include <unordered_map>
typedef std::unordered_map<std::type_index, int> tmap;
int main()
{
tmap m;
m[typeid(main)] = 12;
m[typeid(tmap)] = 15;
}
关于c++ - 使用数据类型(类类型)作为映射中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9859390/