SPM*_*PMP 2 c++ templates c++11 c++14
我正在尝试为矢量定义一个哈希.我有一个简单类型的主要模板,以及具有的类的专门化operator().但是,我收到一个错误template parameters not deducible in partial specialization.有人可以指出为什么?
template <typename T> struct hash<vector<T>>
{
size_t operator()(const vector<T> &x) const
{
size_t res = 0;
for(const auto &v:x) {
boost::hash_combine(res,v);
}
return res;
}
};
template <typename T> struct hash<vector<enable_if_t<true_t<decltype(sizeof(declval<T>()()))>::value, T>>>
{
size_t operator()(const vector<T> &x) const
{
size_t res = 0;
for(const auto &v:x) {
boost::hash_combine(res,v());
}
return res;
}
};
Run Code Online (Sandbox Code Playgroud)
我不喜欢这里的部分特化,特别是因为它会导致代码重复.
template <typename T>
struct hash<vector<T>>
{
template<class T>
static auto call_if_possible(const T& t, int) -> decltype(t()) { return t(); }
template<class T>
static auto call_if_possible(const T& t, ...) -> decltype(t) { return t; }
size_t operator()(const vector<T> &x) const
{
size_t res = 0;
for(const auto &v:x) {
boost::hash_combine(res,call_if_possible(v, 0));
}
return res;
}
};
Run Code Online (Sandbox Code Playgroud)
(如果这hash是实际的std::hash,则答案是"不要这样做".除非专门化取决于用户定义的类型,否则您可能不会专门化标准库模板.)