3

How comes that std::hash does not exist for const std::string?

#include <string>
#include <functional>

int main() {
    std::hash<std::string> hasher1;       // works
    std::hash<const std::string> hasher2; // does not work
}

As expected, I can use the regular std::string specialization for example in a hash map:

#include <string>
#include <functional>
#include <unordered_map>

int main() {
    std::unordered_map<const std::string, int, std::hash<std::string>> a;
}

I feel like there is a better reason than "Well, they just didn't do it" to the const specialization missing. What is it?

6
  • 2
    Just a guess but an some point they had to stop the specialisations: en.cppreference.com/w/cpp/utility/hash Commented Jul 7, 2017 at 13:28
  • 1
    Well, they just didn't do it. Commented Jul 7, 2017 at 13:28
  • 1
    Doesn't operator() of a hash struct take a const argument anyway? Try passing a const string to your second example. It will probably work, meaning that it would have been redundant to specialize for const. Commented Jul 7, 2017 at 13:36
  • 1
    Why do you have unordered_map<const std::string, int> instead of just unordered_map<std::string, int>? Commented Jul 7, 2017 at 13:54
  • Yes, it does. That's why the unordered_map in the second snippet works as well. I am just surprised that those specializations did not exist. Commented Jul 7, 2017 at 13:54

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.