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

你说的曾经没有我的故事 提交于 2019-11-29 15:34:22

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!