std ::使用sfinae哈希专用化? [英] std::hash specialization using sfinae?
问题描述
作为练习,我试图查看是否可以使用SFINAE为 std :: pair创建
和 std :: hash
专业化 std :: tuple
的所有模板参数均为无符号类型时。我对它们有一点经验,但是据我了解,哈希函数需要已经使用 typename Enabled = void
进行模板化,以添加专门化知识。我不太确定该从哪里去。
As an exercise I was trying to see if I could use SFINAE to create a std::hash
specialization for std::pair
and std::tuple
when all of its template parameters are of an unsigned type. I have a little experience with them, but from what I understand the hash function needs to have already been templated with a typename Enabled = void
for me to add a specialization. I'm not really sure where to go from here. Here's an attempt which doesn't work.
#include <functional>
#include <type_traits>
#include <unordered_set>
#include <utility>
namespace std {
template <typename T, typename Enabled = void>
struct hash<std::pair<T, T>, std::enable_if_t<std::is_unsigned<T>::value>>
{
size_t operator()(const std::pair<T, T>& x) const
{
return x;
}
};
}; // namespace std
int
main(int argc, char ** argv)
{
std::unordered_set<std::pair<unsigned, unsigned>> test{};
return 0;
}
错误:
hash_sfinae.cpp:7:42: error: default template argument in a class template partial specialization
template <typename T, typename Enabled = void>
^
hash_sfinae.cpp:8:8: error: too many template arguments for class template 'hash'
struct hash<std::pair<T, T>, std::enable_if_t<std::is_unsigned<T>::value>>
这与我的预期差不多,因为我正在尝试将模板参数扩展为哈希...但是我不确定当时处理这些情况的技术。有人可以帮我理解吗?
It's about what I expected because I'm trying to extend the template parameters to hash... But I'm not sure the technique to handle these cases then. Can someone help me understand?
推荐答案
您不应该专门研究 std :: hash
用于不依赖于您自己定义的类型的类型。
You are not supposed to specialize std::hash
for types that doesn't depend on a type you defined yourself.
也就是说,这种破解可能有效:
That said, this hack might work:
template<class T, class E>
using first = T;
template <typename T>
struct hash<first<std::pair<T, T>, std::enable_if_t<std::is_unsigned<T>::value>>>
{
size_t operator()(const std::pair<T, T>& x) const
{
return x;
}
};
不过,确实不要这样做。编写自己的哈希器。
Really, though, don't do this. Write your own hasher.
这篇关于std ::使用sfinae哈希专用化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!