带有泛型键的c++ std::map类
c++ std::map class with generic key
我有一个类族,每个子类都需要一个映射,但是键具有不同的类型,尽管它们都将对映射执行完全相同的操作。两种情况下的值都是string。到目前为止,我有类似于下面示例的代码,我的目标是重用代码,通过具有通用密钥。不使用STL
以外的任何其他库class A{
public:
/*
* More code
*/
};
class subA1 : public A{
public:
void insertValue(long id, std::string& value){
if(_theMap.find(id) == _theMap.end())
{
_theMap[id] = value;
}
}
private:
std::map<long,std:string> _theMap;
};
class subA2 : public A{
public:
void insertValue(std::string& id, std::string& value){
if(_theMap.find(id) == _theMap.end())
{
_theMap[id] = value;
}
}
private:
std::map<std::string,std:string> _theMap;
};
只需将超类A作为模板,将_theMap和insertValue()移到其中,并在子类中使用正确的模板版本。
template <typename KeyT>
class A{
public:
void insertValue(KeyT id, std::string& value){
if(_theMap.find(id) == _theMap.end())
{
_theMap[id] = value;
}
}
private:
std::map<KeyT, std:string> _theMap;
};
class subA1 : public A<long> {};
class subA2 : public A<std::string> {};
可以将subA1
和subA2
合并为一个模板类,例如:
class A{
public:
/*
* More code
*/
};
template <typename KeyType>
class subA : public A {
public:
void insertValue(const KeyType &id, const std::string& value) {
if(_theMap.find(id) == _theMap.end()) {
_theMap.insert(std::make_pair(id, value));
}
}
private:
std::map<KeyType, std:string> _theMap;
};
然后可以根据需要创建类型定义:
typedef subA<long> subA1;
typedef subA<std::string> subA2;
或者,如果您需要实际的派生类:
class subA1 : public subA<long>
{
...
};
class subA2 : public subA<std::string>
{
...
};
如何写另一个小的基类,说C<T>
,这是一个template typename T
,只包括map<T, string>
和你的insert
函数。那么A的每个新子类也将是C
的一个子类。所以你的subA1
就是public A, public C<long>
等等
相关文章:
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 使用一个考虑到std::map中键值的滚动或换行的键
- 有没有办法对std::unordered_set、std::unrdered_map、std::set、std::map
- 将重物插入std::map
- 使用通用值初始化 std::map,不重复
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- C++:当所有条目都保证是唯一时,替代 std::map
- 使用模板化的键类型定义 std::map,该键类型基于作为参数接收的函数
- 如果 KEY 是 std::list 或 std::vector 而不是值,那么 std::map 的默认行为是什么?
- C++如何创建 std::map
- 从其他容器中移动构造"std::map"
- 将 std::map::emplace 与返回 shared_ptr 的函数一起使用是否正确?
- C++中 std::map 的运行时复杂度是多少?
- 为什么在 std::map 上移动无法将元素从一个映射移动到另一个映射
- 使用重载 [] 运算符返回 std::map() 的可赋值
- std::map, std::unordered_map - 缩小初始值设定项列表中的转换范围
- C++ 使用枚举类对象分配 std::map 值
- 静态 std::map instatiation 在类的方法中调用构造函数吗?
- std::map:当元素不可默认构造时创建/替换元素
- Arduino编译器和STL:使用std::vector和std::map