繁体   English   中英

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

[英]Using an object reference as a key in std::unordered_map

我想知道是否可以在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 :: __详细:: _ Map_base <_key,_Pair,性病:: _ Select1st <_Pair>,真实,_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 :: _ 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]'

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

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

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

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

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

有关使用std::reference_wrapper作为std::map键的更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM