【问题标题】:Use data type (class type) as key in a map使用数据类型(类类型)作为映射中的键
【发布时间】: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_NDerivedType 之间创建一个映射。 每当创建 Derived_N 时,此映射会查找特定 Derived_NDerivedType 是否已存在并返回,否则创建新的并存储在映射中。

实际问题: 有没有办法在地图中将std::mapdata 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; }
};

因为我的问题是如何在地图中使用数据类型,所以我会标记你的一些答案,谢谢

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    C++11 通过在&lt;typeindex&gt; 中提供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;
    }
    

    【讨论】:

      【解决方案2】:

      您可以直接使用typeid(object),因为有type_info::before,如果您使用type_info作为map中的key,可以将其用作比较器,请参见What is `type_info::before` useful for?。无需获取.name()

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          猜你喜欢
          • 2012-02-24
          • 2011-11-12
          • 1970-01-01
          • 1970-01-01
          • 2019-01-18
          • 1970-01-01
          • 1970-01-01
          • 2010-12-20
          • 1970-01-01
          相关资源
          最近更新 更多