使用数据类型(类类型)作为映射中的键

Use data type (class type) as key in a map

本文关键字:映射 数据类型 类型      更新时间:2023-10-16

我有类Base和类Derived_1Derived_2...我需要派生类才能有一个 id。这些 id 用于进一步查找等,因此需要连续(而不仅仅是一些随机数(。因为派生类是由用户创建的,所以 id 不能是 Derived_N 的成员。于是我想出了DerivedType课。

class DerivedType
{
    static unsigned id;
    unsigned m_id;
public:
    DerivedType() : m_id(id++) {  }
}

现在我想在Derived_NDerivedType之间创建一个映射。每当创建Derived_N时,此映射都会查找特定Derived_NDerivedType是否已存在并返回它,否则在映射中创建新的和存储。

实际问题:有没有办法使用数据类型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,通过派生类型

编辑2 - 我的答案我为我的问题找到了更好的解决方案...它是这样的:

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

由于我的问题是如何在地图中使用数据类型,我将标记您的一些答案,谢谢

C++11 通过在 <typeindex> 中提供 std::type_index 来解决这个问题,这是一个可复制、可比较和可散列的对象,由一个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;
}

你可以直接使用typeid(object),因为有 type_info::before ,如果你在映射中使用type_info作为键,它可以用作比较器,请参阅"type_info::before"有什么用?。无需.name().

您可以使用任何您想要的类型或类作为std::map键,前提是您为模板参数提供一个比较函数,告诉它如何对底层树进行排序。

恕我直言,将日期表示为键的最简单方法是将它们转换为 unix 时间戳,但无论它们的类表示是什么,只需提供与映射定义的比较函数即可。