我正在使用 C++ 开发一个(非常)简单的类,它有一个 unordered_map
成员:
class SDLFontManager : public CPObject, public FontManagerProtocol {
public:
SDLFontManager() {};
// flush the cache when the manager is destroyed
virtual ~SDLFontManager() { flushFontCache(); };
// load a font from the cache if it exists, or load it from file and cache it.
virtual FontProtocol* fontWithTTF(const char* filename) {
if(_cache.find(filename) != _cache.end()) {
return _cache[filename];
}
SDLFont* font = new SDLFont(filename);
_cache[filename] = font;
font->retain();
return font;
}
// flush the font cache
virtual void
flushFontCache() {
for(auto font: _cache) {
font.second->release();
}
}
private:
std::unordered_map<std::string, SDLFont*> _cache;
};
当我编译时,我在类的源代码中没有发现任何错误,但 clang 失败,将我指向 C++ 标准库的 functional
文件,包含以下消息:
functional:2441:5: Static_assert failed "This hash only works for enumeration types"
我假设 unordered_map
所需的哈希函数有问题(如果我是正确的,它是作为 HashMap 实现的)。当我用一个简单的 map
替换它时,一切都正确编译。我还有其他unordered_map
在我的代码库中有 std::string
作为完美编译的 key 。
是否有一些我没有发现的明显错误?我非常怀疑这是一个标准库错误。
(如果有任何帮助,代码是用 clang-700.0.65
编译的( Apple LLVM version 7.0.0
,随 Xcode 7 一起提供),没有异常(exception)/RTTI,和 std=c++14
)
编辑
正如@dau_sama 的回答所指出的,<string>
没有直接包含(仅通过包含另一个 header ),这是导致问题的原因。可能的重复项相对不同,如 std::string
不是自定义类,标准库为其提供哈希函数。
最佳答案
您可能缺少字符串标题
#include <string>
应该可以解决你的问题
关于c++ - 此哈希仅适用于枚举类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32121497/