如何专门化std ::哈希从其他库的类型 [英] How to specialize std::hash for type from other library

查看:164
本文介绍了如何专门化std ::哈希从其他库的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我使用的库有一个枚举(说它叫做 LibEnum )。我需要一个 std :: unordered_set LibEnum ,但我得到编译错误,没有专门的 std :: hash 。我可以很容易地写它,只返回数值(第一个元素是0,第二1等),但在哪里我应该把这个专业化,它应该是什么样子?我不能修改库来源。

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 error that there is no specialized std::hash for it. I could easily write it and just return the number of value (first element is 0, second 1 etc), but where exactly I should put this specialization and how should it look like? I can't modify the library sources.

  enum LibEnum { A, B, C, D};
  std::unordered_set <LibEnum> mySet;
  //need std::hash for LibEnum
  //how should it look like?


推荐答案

:: hash :

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

或者,您可以定义 hash 类型,其中你喜欢,只是提供它作为额外的模板参数时实例化 std :: unordered_map< FooEnum>

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.

这篇关于如何专门化std ::哈希从其他库的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆