C++11: Are there reasons why some Regular Types should not have `std::hash` specialised?

给你一囗甜甜゛ 提交于 2019-12-06 17:25:35

问题


With a Regular Type, I mean the definition of Stepanov in Elements of Programming, basically, that there's the concept of equality and that objects which are copies of each other compare equal.

So when you have a Regular Type T, and the equality relation is transitive (a == b && b == c => a == c), you can define a (non-trivial) hash function which is consistent with the definition of equality (a == b => h(a) == h(b)). Always.

But the standard doesn't include many std::hash specialisations. E.g. std::complex doesn't have one, and neither have the containers, with the notable exceptions of vector<bool> and bitset.

So I'm wondering what the design principle is here.

Or, asked differently: Are there reasons not to provide std::hash specialisations for your own types, provided they are regular and equality is transitive?


回答1:


Yes.

When a type has the following two properties I do not think you should define std::hash:

  • There is no efficient way to consistently create a quality hash that covers all the data used to describe equality.

  • There is no efficient and/or intuitive way to select a consistent subset of data to hash.




回答2:


Providing specialization for own types makes no sense, if they're template classes, since the hash function (with high a very high probability) also depends on the template parameters' types, which are unknown.

It there are no template parameters, or the template parameters are restricted to certain types

// provide no implementation to restrict all types
template<typename T> container;

// int is allowed
template<> container<int> {
    ...
}

// double is allowed
template<> container<double> {
    ...
}

providing a specialization of std::hash is possible, since the implementations of the classes (or the instanced template classes) are known, as it is for vector<bool> contrary to complex<T>.



来源:https://stackoverflow.com/questions/29969322/c11-are-there-reasons-why-some-regular-types-should-not-have-stdhash-spec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!