1

我想要一个具有以下结构的类:

class A {
public:
  struct key_type {};

private:

  std::unordered_map<key_type, some_other_type> m;

}

据我了解,要完成这项工作,我需要专门化std::hash,并且声明了std::equal_to之前A::mA::key_type声明了之后,这使得它不可能,因为我无法将模板专门化为 A. Afaik,也没有办法转发声明(在A定义之外)A::key_type

本质上我的问题是:我是否遗漏了什么,或者这种结构是不可能的?

4

1 回答 1

1

有几种方法可以解决这种情况。

  1. 定义一个单独的类型。

    struct A_key_type {};
    namespace std {
        template <> struct hash<A_key_type> { size_t operator()(const A_key_type&); };
    }
    
    class A {
        typedef A_key_type key_type;
        std::unordered_map<key_type, int> m;
    };
    
  2. 提供明确的自定义哈希类型。

    class A {
        struct key_type {};
        struct key_type_hasher { size_t operator()(const key_type&); };
        std::unordered_map<key_type, int, key_type_hasher> m;
    };
    
于 2013-04-01T19:38:55.770 回答