使用sfinae的std :: hash专业化?

Bri*_*uez 8 c++ sfinae template-specialization c++14

作为练习,我试图看看是否可以使用SFINAE创建std::hash专门化,std::pair并且std::tuple当其所有模板参数都是无符号类型时.我对它们有一点经验,但据我所知,哈希函数需要已经模板化,typename Enabled = void我可以添加一个特化.我不确定从哪里开始.这是一种无效的尝试.

#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;
}
Run Code Online (Sandbox Code Playgroud)

错误:

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>>
Run Code Online (Sandbox Code Playgroud)

这是我的预期,因为我正在尝试将模板参数扩展为哈希...但我不确定那时处理这些情况的技术.有人可以帮我理解吗?

T.C*_*.C. 11

您不应该专注std::hash于不依赖于您自己定义的类型的类型.

也就是说,这个黑客可能会起作用:

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;
    }
};
Run Code Online (Sandbox Code Playgroud)

但是,真的,不要这样做.写你自己的哈希.