Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can std::hash be used to hash function pointers?

Tags:

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!

like image 894
templatetypedef Avatar asked Nov 01 '13 02:11

templatetypedef


People also ask

What does std :: hash do?

std::hash<const char*> produces a hash of the value of the pointer (the memory address), it does not examine the contents of any character array.

Can you hash a pointer C++?

Is it safe to use? Is this good practice? you probably mean std::unordered_map and the answer is practicaly the same: you can use pointers if you really mean to hash pointers (and not the object they point to). You can as well implement your own hash (or hash-redirection) to work with the pointed-to objects.

How do you write a hash function in C++?

public int hashCode() Returns a hash code for this string. The hash code for a String object is computed as s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation.


1 Answers

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:

#include <functional>
#include <iostream>

void func1(int) {}
void func2(int) {}

int main()
{
    typedef void (*func_type) (int);

    std::hash<func_type> hash;

    std::cout << hash(func1) << std::endl;
    std::cout << hash(func2) << std::endl;

}

I'd be really interested if anyone has any references to the standard to back this up though.

like image 115
Tristan Brindle Avatar answered Sep 18 '22 13:09

Tristan Brindle