I had to do the following to be able to use string views to poke at
unordered maps with strings for their keys.
I was expecting to simply be able to use std::hash<void>, but gcc 11.2 was
not happy. And I find no evidence of std::hash<void>'s existence on
cppreference.com.
So, does it exist but not documented, and not implemented in gcc, or is this
a rather glaring hole in the standard.
If I can have std::equal_to<void>, I see no reason not to have
std::hash<void>, instead of resorting to such hackery:
#include <unordered_map>
#include <string>
#include <string_view>
#include <utility>
#include <iostream>
struct transparent_hash {
template<typename T,
typename=std::void_t<decltype(
std::hash<std::remove_cvref_t<T>>{}(
std::declval<std::remove_cvref_t<T> &>()
))>>
auto operator()(T && t) const
{
std::hash<std::remove_cvref_t<T>> h;
return h(std::forward<T>(t));
}
typedef void is_transparent;
};
std::unordered_map<std::string, int,
transparent_hash,
std::equal_to<void>> lookup;
auto find(const std::string_view &f)
{
return lookup.find(f);
}
int main()
{
lookup[std::string{"a"}]=4;
if (find("a")->second == 4)
{
std::cout << "It works" << std::endl;
}
return 0;
}