Can the C++11 std::hash
type be used to hash function pointers? There is a hash
partial specialization defined as
template <typename T> struct hash<T*>;
but since function pointers are different from other pointer types in C++ (e.g. they can't be cast to void*
), I'm not sure whether it is safe to use it for types like int(*)()
or void(*)(int, int)
.
Is this permitted? Is there any specific wording in the new ISO spec that supports or refutes this?
Thanks!
It's actually interesting... I bumped into this question while using MSVC++. What I'm trying to do is:
with Fun a function pointer type.
During compilation, I get the following error:
In a previous attempt I attempted to cast the function pointer to
void*
, which isn't allowed and doesn't compile (see: https://isocpp.org/wiki/faq/pointers-to-members#cant-cvt-memfnptr-to-voidptr for details). The reason is that a void* is a data pointer, while a function pointer is a code pointer.My conclusion so far is that it isn't allowed and it won't compile on MSVC++.
Great question. I don't know the answer for sure, and I'm happy to defer to anyone with better knowledge than me, but my thinking is that even though function pointers aren't the same as data pointers, they are pointers nonetheless: so the
std::hash<T*>
partial specialisation should be applied.For what it's worth, the following compiles without warnings even with
-pendantic
in g++ 4.8.1 and clang 3.3, and works as expected:I'd be really interested if anyone has any references to the standard to back this up though.
I found the following:
And then, the referenced 20.8 states:
It kind of states it backwards... but the statement not only makes algorithmic templates work with pointers to functions... seems appropriate for your question.