任何枚举类型的C++ 11哈希函数

Dra*_*ter 10 c++ enums templates hash-function c++11

我正在为我的对象编写一个哈希函数.由于所有STL容器的Generic Hash功能,我已经可以散列容器并组合散列.但我的课程也有枚举.当然我可以为每个枚举创建一个哈希函数,但这似乎不是一个好主意.是否可以为其创建一些通用规范std::hash,以便它可以应用于每个枚举?类似的东西,使用std::enable_ifstd::is_enum

namespace std {
  template <class E>
  class hash<typename std::enable_if<std::is_enum<E>::value, E>::type> {
  public:
    size_t operator()( const E& e ) const {
      return std::hash<std::underlying_type<E>::type>()( e );
    }
  };
};
Run Code Online (Sandbox Code Playgroud)

PS.此代码无法编译

error: template parameters not used in partial specialization:
error:         ‘E’
Run Code Online (Sandbox Code Playgroud)

Joh*_*itb 11

您的E参数无法推断,因为编译器无法知道您的enable_if<...>::type最终E再次表示(实际上,它有一些特殊的设计不会这样做!).它被称为"非演绎的上下文" E.

如果hash只有一个参数,则没有办法(我知道)SFINAE你的部分专业化.