Specializing std::hash
To leverage unordered containers with user-defined key types, such as std::unordered_set
Upon investigating various resources, including the C Standard, it becomes apparent that it is possible to specialize std::hash
namespace std { template <> inline size_t hash<X>::operator()(const X& x) const { return hash<int>()(x.id); } }
Now, let's address the questions raised:
1. Legality of Specialization
Adding specializations to the std namespace is not only permitted but encouraged. It allows for the extension of standard capabilities to support user-defined types.
2. Compliant Version of std::hash
The correct syntax for specializing std::hash
namespace std { template <> struct hash<X> { size_t operator()(const X& x) const { // Your custom hash function implementation } }; }
3. Portable Solution
The std::hash specialization demonstrated earlier requires C 11 compatibility, which may not be universally supported by compilers. For increased portability, consider using a non-standard namespace, e.g.:
namespace ht { template <> struct hash<X> { // Your custom hash function implementation }; }
The above is the detailed content of How Can I Specialize `std::hash::operator()` for Custom Types in C ?. For more information, please follow other related articles on the PHP Chinese website!