Home >Backend Development >C++ >How Can I Specialize `std::hash` for My User-Defined Types in C ?

How Can I Specialize `std::hash` for My User-Defined Types in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-10 03:19:16175browse

How Can I Specialize `std::hash` for My User-Defined Types in C  ?

Specializing std::hash for User-Defined Types in Unordered Containers

To enable the use of custom key types in std::unordered_set and std::unordered_map, one must provide both an equality operator and a hash function. This typically involves defining a custom struct or class that implements these operators. However, it would be more convenient to use a default hash function for user-defined types, similar to the built-in types provided by the compiler and library.

According to the C Standard Draft N3242 and Boost.Unordered, it is possible to specialize std::hash for a custom type. This involves adding a specialization to the std namespace:

namespace std {
  template <>
  inline size_t hash<X>::operator()(const X& x) const { return hash<int>()(x.id); }
}

In this example, the hash function for type X is specialized to use the hash function for type int, which assumes that X has a member variable id. It is important to note that the hash function must be specialized for the specific template argument type, and the resulting hash value must be consistent with the equality operator for the type.

Legality and Portability:

  • Is it legal to add a specialization to std? Yes, it is legal to add specializations to std as long as one of the involved types is user-defined.
  • Which version of std::hash::operator() is compliant with C 11? The correct way to specialize std::hash in C 11 is to define a specialization of the struct std::hash:
namespace std {
  template <> struct hash<X> {
    size_t operator()(const X& x) const { return hash<int>()(x.id); }
  };
}
  • Is there a portable way to do it? The code provided above should be portable across different compilers that support C 11.

The above is the detailed content of How Can I Specialize `std::hash` for My User-Defined Types in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn