可视 C2338:C++ 标准不为此类型提供带有字符串和unique_ptr的哈希

visual C2338: The C++ Standard doesn't provide a hash for this type with string and unique_ptr

本文关键字:字符串 unique 哈希 ptr C++ C2338 标准 类型 可视      更新时间:2023-10-16

我正在尝试实现一个以std::string为键、std::unique_ptr为值的std::unordered_map。然而,当我尝试编译时,我得到了错误:

error C2338: The C++ Standard doesn't provide a hash for this type.

环顾不同的问题,我知道C++11确实包含一个std::hash<std::string>,我看不出为什么会抛出这个错误。我已经尝试实现我自己的散列函数,就像这里看到的那个,但它仍然抛出相同的错误。我还尝试过使用__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。

非常感谢您的帮助。谢谢

EDIT:添加AtlasTexture类:标头和实现

编辑:我的移动和移动任务的实现:在这里。

您是否尝试过在AtlasTexture中实现所有编译生成的方法?

我的问题是如何将std::unique_ptr放置到地图中。放置它的最佳方式是使用map::emplace()而不是map::insert()。这是因为std::unique_ptr没有复制构造函数,模板移动对象而不是复制它。感谢@Casey的回答。

我的另一个问题是使用新的auto类型,以便从映射中获得对。同样,由于unique_ptr无法复制,当auto更改为std::pair时会发生这种情况,因此会引发编译器错误。解决这个问题的简单方法是使用auto&而不是auto。感谢@MatthieuM。为此。