Jea*_*pas 9 c++ libstdc++ c++11 libc++
我想知道是否可以在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;
Run Code Online (Sandbox Code Playgroud)
在尝试编译这个简单的代码片段时,我遇到了一些关于方法重新定义的错误:
使用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),我没有这个问题.
这是新标准规定的一些限制,如果是这样,为什么?
有没有办法解决这个限制?
Mat*_* M. 11
新标准定义std:reference_wrapper<T>
解决此限制.
它可以隐式转换T&
为透明,并且像引用一样保证没有null
状态,但是与引用不同,它可以重新定位.
更多信息使用std::reference_wrapper
为重点std::map
.