Using object reference as key in std :: unordered_map

I would like to know if it is possible to use an object reference as a key in an unordered_map container in C ++.

#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; 

While trying to compile this simple snippet, I got some errors regarding method overrides:

Using clang with libC ++

/ usr / include / C ++ / v1 / unordered_map: 352: 12: error: class member cannot be updated

size_t operator () (const _Cp & __x) const

Using gcc 4.6 with libstdc ++

/usr/include/++/4.6/bits/hashtable_policy.h: 556: 5: error: '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, stand :: __ 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] cannot be overloaded

/usr/include/++/4.6/bits/hashtable_policy.h: 537: 5 : error: with '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 = standard :: _ Hashtable, std :: allocator>, std :: _ Select1st>, std :: equal_to, object_hash, std :: __ detail :: _ Mod_range_hashing, standard :: __ 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]

If I use the old gnu hash_map (__gnu_cxx :: hash_map) instead, I don't have this problem.

Is this some limitation imposed by the new standard, and if so, why?

Is there a way around this limitation?

+7
source share
1 answer

The new standard defines std:reference_wrapper<T> to get around this limitation.

It is implicitly converted to T& so that it is transparent, and, like links, ensure that the state is null , but unlike links, it can be reinstalled.

Additional information in Using std::reference_wrapper as a key in std::map .

+10
source

All Articles