使用带有std :: pair枚举类的unordered_map作为键的不完整类型struct std :: hash无效

时间:2015-08-28 08:54:02

标签: c++ c++11 unordered-map enum-class

我想使用unordered_map<std::pair<enum_class,other_enum_class>,std::uint8_t>来管理一些像素图格式。

这里是最小的代码:

#include <unordered_map>
#include <utility>
#include <cstdint> 
#include <iostream>
#include <functional>

enum class PNM : std::uint8_t { PBM, PGM, PPM };
enum class Format : bool      { BIN, ASCII };

struct pair_hash {
public:
    template <typename T, typename U>
    std::size_t operator()(const std::pair<T, U> &x) const { 
        return std::hash<T>()(x.first) ^ std::hash<U>()(x.second); 
    }
};

int main(){

    std::unordered_map<std::pair<PNM, Format>, std::uint8_t, pair_hash> k_magic_number ({
        { { PNM::PBM, Format::BIN   }, 1 }, { { PNM::PGM, Format::BIN   }, 2 }, { { PNM::PPM, Format::BIN   }, 3 },
        { { PNM::PBM, Format::ASCII }, 4 }, { { PNM::PGM, Format::ASCII }, 5 }, { { PNM::PPM, Format::ASCII }, 6 }
    });

    std::cout << k_magic_number[std::make_pair<PNM, Format>(PNM::PBM, Format::BIN)];
}

使用GCC,当我尝试实例化类时,我有一个error

  

main.cpp:14:24:错误:无效使用不完整类型&#struct struct std :: hash&#39;
     return std :: hash()(x.first)^ std :: hash()(x.second);
  在包含的文件中   /usr/local/include/c++/5.2.0/bits/basic_string.h:5469:0,
                   来自/usr/local/include/c++/5.2.0/string:52,
  [...]

对于Clang我也有一个error

  

错误:未定义模板的隐式实例化&#st; :: hash&#39;                   return std :: hash()(x.first)^ std :: hash()(x.second);   /usr/local/bin/../lib/gcc/x86_64-unknown-linux-gnu/5.2.0/../../../../include/c++/5.2.0/bits/hashtable_policy。 H:1257:16:   注意:在实例化函数模板专业化   &#39; pair_hash ::运算符()&#39;这里要求   [...]

使用VS2013我没有错误,代码编译并执行。

我的代码中缺少什么?

1 个答案:

答案 0 :(得分:8)

g ++ - 5给出以下错误:

  

无效使用不完整类型struct std::hash<PNM>

     

无效使用不完整类型struct std::hash<Format>

因此,您应该为std::hashPNM专门设置Format

namespace std {
template<>
struct hash<PNM>
{
   typedef PNR argument_type;
   typedef size_t result_type;

   result_type operator () (const argument_type& x) const
   {
      using type = typename std::underlying_type<argument_type>::type;
      return std::hash<type>()(static_cast<type>(x));
   }
};

template<>
struct hash<Format>
{
   typedef Format argument_type;
   typedef size_t result_type;       

   result_type operator () (const argument_type& x) const
   {
      using type = typename std::underlying_type<argument_type>::type;
      return std::hash<type>()(static_cast<type>(x));
   }
};

}

或者你可以编写模板结构,它只适用于enums使用SFINAE(不确定,它不是标准的UB,因为它实际上不是专业化)。

namespace std
{

template<typename E>
struct hash
{
   typedef E argument_type;
   typedef size_t result_type;
   using sfinae = typename std::enable_if<std::is_enum<E>::value>::type;

   result_type operator() (const E& e) const
   {
      using base_t = typename std::underlying_type<E>::type;
      return std::hash<base_t>()(static_cast<base_t>(e));
   }
};

}
相关问题