我正在尝试将std::hash
专门用于专业课程。到目前为止,最好的方法是基于this answer:
#include <type_traits>
#include <functional>
#include <unordered_set>
namespace foo
{
template<class T, class E>
using first = T;
struct hashable {};
struct bar : public hashable {};
}
namespace std
{
template <typename T>
struct hash<foo::first<T, std::enable_if_t<std::is_base_of<foo::hashable, T>::value>>>
{
size_t operator()(const T& x) const { return 13; }
};
}
int main() {
std::unordered_set<foo::bar> baz;
return 0;
}
使用g ++ 5.2.0编译时没有警告(-Wall -pedantic
),但是使用clang ++ 3.7.0会导致以下错误:
first.cpp:17:12: error: class template partial specialization does not specialize any template argument; to define the primary template, remove the template argument list
struct hash<foo::first<T, std::enable_if_t<std::is_base_of<foo::hashable, T>::value>>>
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
这是编译错误还是代码错误?
This question,提出了一个SFINAE解决方案,它在技术上适用于我的gcc和clang版本。但是,因为它只禁用了运算符而不是类,当一个人试图对任何不可散列的类进行散列时,它会开始产生非常令人困惑的错误消息:
template <typename T>
struct hash
{
typename std::enable_if_t<std::is_base_of<foo::hashable, T>::value, std::size_t>
operator()(const T& x) const { return 13; }
};
...
struct fail {};
std::unordered_set<fail> bay;
...
type_traits:2388:44: error: no type named 'type' in 'std::enable_if<false, unsigned long>';
'enable_if' cannot be used to disable this declaration
我不想考虑宏观解决方案。我进一步尝试了以下方法:
template <typename T>
struct hash<std::enable_if_t<std::is_base_of<foo::hashable, T>::value, T>>
两个编译器都抱怨说他们无法推断出类型,我觉得这很令人恼火,因为我对first
解决方案没有太大的区别。
我的第一次尝试是enable_if
的通常模式:
template <typename T,
typename DUMMY = std::enable_if_t<std::is_base_of<foo::hashable, T>::value>>
struct hash<T>
在类模板部分特化中使用默认模板参数失败。
是否有一种干净的模板元编程方法可以在C ++ 14中实现这一点?
答案 0 :(得分:3)
首先有点咆哮:
std :: hash的设计非常糟糕。不允许部分专业化。委员会应该完全复制提升实施。
(咆哮)
我认为一个优雅的解决方案是从不同的角度来看待它:
#include <type_traits>
#include <functional>
#include <unordered_set>
namespace foo
{
template<class T, class E>
using first = T;
struct hashable {};
struct bar : public hashable {};
template<class T, typename = void>
struct hashable_hasher;
template<class T>
struct hashable_hasher<T, std::enable_if_t<std::is_base_of<hashable, T>::value>>
{
size_t operator()(const T& x) const { return 13; }
};
template<class T, typename = void>
struct choose_hash {
using type = std::hash<T>;
};
template<class T>
struct choose_hash<T, std::enable_if_t<std::is_base_of<hashable, T>::value>> {
using type = hashable_hasher<T>;
};
template<class T>
using choose_hash_t = typename choose_hash<T>::type;
template<class T>
using choose_set_t = std::unordered_set<T, choose_hash_t<T>>;
}
int main() {
foo::choose_set_t<foo::bar> baz;
return 0;
}