如何为来自其他库的类型专门化 std::hash

How to specialize std::hash for type from other library(如何为来自其他库的类型专门化 std::hash)

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

问题描述

所以我使用的库有一个枚举(假设它名为LibEnum).我需要有一个 LibEnum 的 std::unordered_set,但是我得到编译错误,没有专门的 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?

推荐答案

你可以专门针对你的类型std::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 时将其作为附加模板参数提供::>

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::hash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何为来自其他库的类型专门化 std::hash

基础教程推荐