Template specialization and constant identifier by type

Why does the compiler expect a separate specialization of the template on (concrete) types Tand const T? Let me set an example. I had an unordered map with a type keyKey

std::unordered_map<Key, Value> data;

and to compile it, I had to specialize std::hashin type Keyas

namespace std {
  template<>
  class hash<Key> { /* implementation */ };
}

However, when I changed the map type to

std::unordered_map<const Key, Value> data;

the compiler did not use my specialization and instead chose a generic one std::hash<T>, which is slightly larger than the compile time statement until I specialize std::hash<const Key>.

Discarding a utility that determines the type of card key with const, why const Tdoesn't it collapse before Twhen looking for specialization in this case?

, std::hash (), ?

+4
1

"", , , , .

. std::unordered_map<const std::string, int>.

, const , value_type std::pair<const Key, Val>; const, . , , volatile .

? . :

template<typename Key,
         typename Val,
         typename Hash  = std::hash<typename std::remove_cv<Key>::type>,
         typename KeyEq = std::equal_to<Key>,
         typename Alloc = std::allocator<std::pair<const Key, Val>>>
using my_unordered_map = std::unordered_map<Key, Val, Hash, KeyEq, Alloc>;

std::remove_cv Hash.

(Live on coliru.)

+2

Source: https://habr.com/ru/post/1620620/


All Articles