使用数据类型(类类型)作为映射中的键
Use data type (class type) as key in a map
我有类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
作为地图中的键?我不怕任何模板元程序解决方案。或者有没有优雅的方法来实现我的目标?
编辑日期类型 ->数据类型,我的意思是像类类型一样,我很抱歉:)
我想像这样使用它:
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 时间戳,但无论它们的类表示是什么,只需提供与映射定义的比较函数即可。
- 防止主数据类型C++的隐式转换
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 在C++中打印指向不同基元数据类型的指针的内存地址
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 如何计算数据类型的范围,例如int
- C++中数据类型修饰符的顺序
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- 特定数据类型的模板类
- 如何使映射键具有两种不同的数据类型?
- 无法构造具有给定数据类型的多映射
- 返回字符串和不同向量数据类型的映射C++
- 添加字符串向量和不同数据类型向量的映射
- (C++,提升::变体)提升变体映射的数据类型并对其执行数学运算
- 使用两种或两种以上数据类型的对象作为c++映射、OOP的关键字
- Java 编程语言中的数据类型如何映射到本机编程语言(如 C 和 C++)中的数据类型
- 使用数据类型(类类型)作为映射中的键
- uint32_t作为映射键的数据类型
- 在c++ /CLI中映射C/ c++数据类型
- 将Windows数据类型映射到.net
- C++std::使用用户定义的数据类型进行映射