Igor R.
Igor R.

Reputation: 15075

Are 2 instances of `std::hash<type>` equivalent?

Assume my_hasher is a hashing function object. Should the following be correct, according to the Standard?

 my_type k;
 assert(my_hasher{}(k) == my_hasher{}(k));

The cppreference states the above assertion is correct.

However, the Standard (16.5.3.4, [hash.requirements]) only requires that for a specific instance of my_hasher,

the value returned shall depend only on the argument k for the duration of the program

...which seems like it permits 2 different instances of my_hasher to return different hash values for the same operand.

So, is cppreference mistaken or am I missing something?

Upvotes: 1

Views: 146

Answers (1)

Caleth
Caleth

Reputation: 62684

The requirements on specialisations of std::hash can be more specific than the requirements in the concept Hash.

Specifically std::hash is required to be DefaultConstructible, whereas general Hashes aren't.

The requirement you are reading is that two default-constructed std::hash<T> objects compute the same hash, not that any two objects of some Hash type compute the same hash.

Upvotes: 2

Related Questions