Call to implicitly deleted default constructor when instantiating unordered_map<const char, std::string>

Viewed 46

I'm trying to instantiate an std::unordered_map<const char, std::string>:

std::unordered_map<const char, std::string> cities = {
    {'A', "Amsterdam"},
    {'B', "Berlin"},
    {'C', "Canberra"}
};

This fails with error: call to implicitly-deleted default constructor of 'std::unordered_map<const char, std::basic_string<char>>::hasher'. It looks like std::hash can't hash const char, but I can't find anything which would confirm it. Why doesn't it work?

1 Answers

As stated in documentation for std::hash it is implemented through template specialization:

Each specialization of this template is either enabled ("untainted") or disabled ("poisoned").

The enabled specializations of the hash template defines a function object that implements a hash function. Instances of this function object satisfy Hash. In particular, they define an operator() const that...

And in section "Standard specializations for basic types" only types like char, int etc are listed, not their const variants. As template specialization for non-const and const versions are different those specializations do not work for const types. So you either need to provide your own specialization for const char or just use std::uinordered_map<char,std::string> which should be used anyway.

Related