Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

std::hash<void>: myth or reality?

26 views
Skip to first unread message

Sam

unread,
Nov 13, 2021, 3:30:22 PM11/13/21
to
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;
}

Bo Persson

unread,
Nov 14, 2021, 3:03:04 AM11/14/21
to
On 2021-11-13 at 21:30, Sam wrote:
> 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:
>

The usual reason for something *not* being in the standard is that
nobody has written a paper to propose it. The standard doesn't write itself.


0 new messages