无序映射中运算符[]的C++专门化
C++ specialization of operator[] in unordered_map
我一直在使用unordered_map<int, myObject>
和指向无序映射中对象的myObject*
指针。这种方法已经运行了一段时间,但我最近发现,我错误地认为添加到无序映射中的myObject的内存位置将始终保持不变。
在无序映射中添加和删除元素时,我可以使用unordered_map<int, myObject*>
、new
和delete
来解决这个问题。
由于我有相当多的代码,我不想在代码中修改无序映射的每个地方都添加new
和delete
,我宁愿尝试重载unordered_map::operator[]
和unordered_map::erase()
,这样new
和delete
的使用就可以透明地进行,而且我不必更改现有的代码。unordered_map::operator[]
然后可以返回对myObject本身的引用,而不是指针。
我试图继承unordered_map
,但我不确定应该如何添加模板参数列表:
using namespace std;
template<class _Kty,
class _Ty,
class _Hasher = hash<_Kty>,
class _Keyeq = equal_to<_Kty>,
class _Alloc = allocator<pair<const _Kty, _Ty> > >
class my_unordered_map : public unordered_map<_Umap_traits<_Kty, _Ty,
_Uhash_compare<_Kty, _Hasher, _Keyeq>, _Alloc, false> >
{
};
但我收到的错误如下:
error C2976: 'std::unordered_map' : too few template arguments
error C2955: 'std::unordered_map' : use of class template requires template argument list
然后我意识到,当将myObject*
类型与unordered_map
一起使用时,可能会向std添加专门化,但我不确定是否有可能用专门化重载operator[]
。
我很感激我能得到的任何帮助,谢谢!
编辑:
我现在已经创建了一个template <class mapped_type>
类,其中unordered_map<int, mapped_type*>
作为内部结构。operator[]
相当简单地包括:
template <class mapped_type> class MyMap {
public:
std::unordered_map<int, mapped_type*> internal_map;
mapped_type& operator[](int&& _Keyval)
{ // find element matching _Keyval or insert with default mapped
mapped_type*& ptr = internal_map[_Keyval];
if (ptr == nullptr) ptr = new mapped_type();
return *ptr;
}
}
void erase(const int& _Keyval)
{ // erase and count all that match _Keyval
mapped_type* ptr = internal_map[_Keyval];
if (ptr) delete ptr;
internal_map.erase(_Keyval);
}
void clear()
{ // erase all
internal_map.clear();
}
现在的问题是擦除方法(默认方法包含在std::_Hash
中)。我真的不需要迭代器,所以我想最好的方法可能是先使用operator[]
方法来找到条目,然后在从internal_map
中删除它之前使用delete
,或者你有其他更合适的想法吗?
编辑:添加了擦除建议。这很有道理,对吧?
要从std::unordered_map
继承,使用就足够了
template <class T,class V>
class MyMap : public unordered_map<T, V>
如果可以使用std分配器和hash函数。但是要注意,在标准容器中没有虚拟析构函数。
不管怎样,在我看来,你最终想要做的事情就像你想要一个侵入性容器。如果是的话,那么就存在这个相关的so问题。
- 是否可以对零模板参数进行模板专门化
- 尝试根据类中 typedef 的存在来专门化模板函数
- 如何基于模板化类的基类专门化成员函数
- 如何为指向复杂值的迭代器专门化算法?
- 专门化模板覆盖函数/避免对象切片
- 我能否根据其运算符()的签名专门化可变参数模板参数
- 如何使用模板化类专门化模板化函数?
- 线程 std::调用未知类型,无法专门化函数错误
- 输入两个不专门化大小的矩阵
- 如何在模板类中专门化赋值运算符?
- 如何专门化容器和枚举的模板
- Clang拒绝类模板的嵌套类仅通过专门化定义的代码是正确的吗
- 取消专门化C++模板参数
- SFINAE的变分变量模板专门化
- 如何在编译时专门化大型模板函数中的小部分
- 如何在c++运算符()中专门化调用模板
- 模板函数,其中一个参数需要专门化,而另一个不需要
- 如何专门化字符串数组的模板?
- 如何专门化模板
- 如何避免为模板化迭代器的每个可能的实例化专门化iterator_traits?