首页 文章

在std :: unordered_map中使用对象引用作为键

提问于
浏览
8

我想知道是否可以在C中的unordered_map容器中使用对象引用作为键 .

#include <unordered_map>

class Object {
    int value;
};

struct object_hash {
  inline size_t operator()(const Object& o) const { return 0; }
};

std::unordered_map<Object&, int, object_hash> map;

在尝试编译这个简单的代码片段时,我遇到了一些关于方法重新定义的错误:

使用clang与libc

/ usr / include / c / v1 / unordered_map:352:12:错误:类成员无法重新声明size_t operator()(const Cp&_ x)const

使用gcc 4.6和libstdc

/ usr / include / c /4.6/bits/hashtable_policy.h:556:5:错误:'std :: __ detail :: _ Map_base <_Key,_Pair,std :: _ Select1st <_Pair>,true,_Hashtable> :: mapped_type& std :: __ detail :: _ Map_base <_Key,_Pair,std :: _ Select1st <_Pair>,true,_Hashtable> :: operator [with Key = Object&, Pair = std :: pair,_Hashtable = std :: _ Hashtable,std :: allocator>,std :: _ Select1st>,std :: equal_to,object_hash,std :: __ detail :: _ Mod_range_hashing,std :: __ detail :: _ Default_ranged_hash,std :: __ detail :: _ Prime_rehash_policy,false,false,true>,std :: __detail :: _ Map_base <_Key,_Pair,std :: _ Select1st <_Pair>,true,_Hashtable> :: mapped_type = int]'无法重载/ usr / include / c /4.6/bits/hashtable_policy.h:537:5:错误:'std :: __ detail :: _ Map_base <_Key,_Pair,std :: _ Select1st <_Pair>,true,_Hashtable> :: mapped_type&std :: __ detail :: _ Map_base <_Key,_Pair,std :: _ Select1st <_Pair> ,true,_Hashtable> :: operator [](const _Key&)[with Key = Object&, Pair = std :: pair,_Hashtable = std :: _ Hashtable,std :: allocator>,std :: _ S elect1st>,std :: equal_to,object_hash,std :: __ detail :: _ Mod_range_hashing,std :: __ detail :: _ Default_ranged_hash,std :: __ detail :: _ Prime_rehash_policy,false,false,true>,std :: __ detail :: _ Map_base <_Key ,_Pair,std :: _ Select1st <_Pair>,true,_Hashtable> :: mapped_type = int]'

如果我使用旧的gnu hash_map(__gnu_cxx :: hash_map),我没有这个问题 .

这是新标准规定的一些限制,如果是这样,为什么?

有没有办法解决这个限制?

1 回答

  • 11

    新标准定义 std:reference_wrapper<T> 以解决此限制 .

    它可以隐式转换为 T& ,因此它是透明的,并且像引用一样保证没有 null 状态,但是与引用不同,它可以重新安装 .

    Using std::reference_wrapper as key in std::map中的更多信息 .

相关问题