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

标签 c++ templates

我有类 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 是否已经存在并返回,否则创建新的并存储在映射中。

实际问题: 有没有办法在 map 中使用 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; }
};

因为我的问题是如何在 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/

相关文章:

c++ - 我应该在移动构造函数中 std::move 一个 shared_ptr 吗?

c++ - 如何从二维数组中获取行和列 C++

c++ - Visual Studio 生成的静态库最大文件大小或其他限制?

javascript - 在 Ember.js 中集成测试路由模板

c++ - Visual C++ Express、调试器、排序关联容器和内存释放

c++ - 使用 POCO C++ 的非阻塞 WebSocket 服务器

c++ - 如何同时别名和实例化模板函数?

c++ - 缩小 C++ 模板代码上的样板代码

php - 有没有办法让所有模板都继承母模板

C++ 将模板类型限制为数字