How to specialize std::hash for type from other library

前端 未结 1 1317
南方客
南方客 2020-12-21 17:49

So the library I use has an enum (say it\'s named LibEnum). I need to have an std::unordered_set of LibEnum, but I get compilation err

相关标签:
1条回答
  • You can just specialise std::hash for your type:

    namespace std {
        template <>
        struct hash<FullyQualified::LibEnum> {
            size_t operator ()(FullyQualified::LibEnum value) const {
                return static_cast<size_t>(value);
            }
        };
    }
    

    Alternatively, you can define a hash type where ever you like and just provide it as the additional template argument when instantiating std::unordered_map<FooEnum>:

    // Anywhere in your code prior to usage:
    
    struct myhash {
        std::size_t operator ()(LibEnum value) const {
            return static_cast<std::size_t>(value);
        }
    };
    
    // Usage:
    
    std::unordered_map<LibEnum, T, myhash> some_hash;
    

    Neither methods require you to modify the library.

    0 讨论(0)
提交回复
热议问题