2012-05-22 2 views
7

C++의 unordered_map 컨테이너에서 객체 참조를 키로 사용할 수 있는지 알고 싶습니다. std :: 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; 

이 간단한 조각을 컴파일하려고

, 나는 방법의 재정에 대한 몇 가지 오류를 가지고 : 된 libstdC++

/usr/include/c++/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, 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]’ cannot be overloaded

/usr/include/c++/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 = 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]’

와 GCC 4.6을 사용하여 libc의 ++

/usr/include/c++/v1/unordered_map:352:12: error: class member cannot be redeclared

size_t operator()(const _Cp& __x) const

와 연타를 사용

대신 이전 gnu hash_map (__gnu_cxx :: hash_map)을 사용하면이 문제가 발생하지 않습니다. .

새로운 표준에서이 제한 사항이 적용됩니까? 그렇다면 그 이유는 무엇입니까?

이 제한 사항을 해결할 방법이 있습니까?

답변

10

새 표준은이 제한을 해결하기 위해 std:reference_wrapper<T>을 정의합니다.

암시 적으로 T&으로 변환되어 투명하게 표시되며 참조가 동일하지 않으므로 null 상태가되지만 참조와 달리 다시 장착 될 수 있습니다.

자세한 내용은 Using std::reference_wrapper as key in std::map.