This hash only works for enumeration types

2019-08-11 16:55发布

问题:

I'm working on a (very) simple class in C++ that has a unordered_map member:

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;
};

When I compile, I get no errors in the class's source, but clang fails, pointing me to the C++ standard library's functional file, with the following message:

functional:2441:5: Static_assert failed "This hash only works for enumeration types"

I assume that there is a problem with the hashing function needed for unordered_map (which, if I am correct, is implemented as a HashMap). When I replace it with a simple map, everything compiles properly. I have other unordered_maps in my codebase with std::string as keys that compile perfectly.

Is there some obvious mistake I've not spotted? I'm highly doubt this would be a standard library bug.

(if it can be of any help, the code is compiled with clang-700.0.65 (Apple LLVM version 7.0.0, shipped with Xcode 7), no exceptions/RTTI, and std=c++14)

edit

As pointed out by @dau_sama's answer, <string> wasn't included directly (only by including another header), which was causing the problem. The possible duplicate is relatively different, as std::string is not a custom class and the standard library provides a hash function for it.

回答1:

You are probably missing the string header

#include <string>

should solve your problem