【发布时间】:2014-03-11 21:55:03
【问题描述】:
我正在尝试实现一个 std::unordered_map,其中 std::string 作为键,std::unique_ptr 作为值。但是,当我尝试编译时,我得到了错误:
error C2338: The C++ Standard doesn't provide a hash for this type.
环顾不同的问题,我知道 C++11 确实包含一个 std::hash ,我看不出为什么会抛出这个错误。我尝试实现自己的哈希函数,就像看到的 here 一样,但它仍然抛出相同的错误。我还尝试使用__declspec(dllexport) 并将包含类的复制构造函数和赋值运算符设为私有,因为在某些线程中建议使 unique_ptr 工作,但无济于事。
这是违规类的代码:
#ifndef __TEXTURE_MAP_H__
#define __TEXTURE_MAP_H__
#include <unordered_map>
#include <vector>
#include <memory>
#include <string>
//__declspec for std::unique_ptr compat.
class /*__declspec(dllexport)*/ TextureMap : virtual public IconRegister
{
private:
uint32 _textureId;
std::unordered_map<const std::string, std::unique_ptr<AtlasTexture> > _registeredIcons;
std::unordered_map<const char*, AtlasTexture*> _uploadedIcons;
std::vector<AtlasTexture*> _animatedIcons;
public:
TextureMap();
~TextureMap();
uint32 getTextureId();
void loadTextureAtlas();
/* override */ IIcon& registerIcon(const char*);
void registerIcons();
private:
TextureMap(const TextureMap& other) { }
TextureMap& operator= (const TextureMap& other) { return *this; };
};
#endif
我找不到任何不应该工作的原因,并且我已经尝试了几乎所有我在搜索问题时可以找到的其他解决方案。
我正在使用 MSVC 2012。
非常感谢任何帮助。谢谢。
编辑:添加 AtlasTexture 类:header 和 implementation
编辑:我的移动和移动分配的实现:here。
【问题讨论】:
-
您的
_registeredIcons密钥不应该是const- 只是普通的旧std::string(hash专门用于string而不是const string)。此外,std::hash(const char*)将散列指针的地址,而不是指向的文本......这真的是你想要的吗? -
好吧,问题在于字符串前面没有 const,我开始收到一个新错误:“ error C2248: 'std::unique_ptr<_ty>::unique_ptr' : cannot access private member在类 'std::unique_ptr<_ty>' " 中声明
-
我认为这是因为
unique_ptr<>不是映射到的有效类型...根据 23.2.5.10 “key_type 和 mapped_type 有时需要为 CopyAssignable” -unique_ptr不是 CopyAssignable。你可以使用shared_ptr。 -
@Praetorian:当然......我认为只有当你使用初始化列表时......这就是为什么我要求查看引发错误的代码行。 GCC 曾经有一个 unique_ptr 的错误,有趣的是 Casey 也怀疑 MSVC。
标签: c++ visual-c++ c++11 hash unordered-map