【发布时间】:2014-02-20 07:10:42
【问题描述】:
我有一个抽象基类Hashable,可以从该类派生散列。我现在想将std::hash 扩展到从Hashable 派生的所有类。
下面的代码应该就是这样做的。
#include <functional>
#include <type_traits>
#include <iostream>
class Hashable {
public:
virtual ~Hashable() {}
virtual std::size_t Hash() const =0;
};
class Derived : public Hashable {
public:
std::size_t Hash() const {
return 0;
}
};
// Specialization of std::hash to operate on Hashable or any class derived from
// Hashable.
namespace std {
template<class C>
struct hash {
typename std::enable_if<std::is_base_of<Hashable, C>::value, std::size_t>::type
operator()(const C& object) const {
return object.Hash();
}
};
}
int main(int, char**) {
std::hash<Derived> hasher;
Derived d;
std::cout << hasher(d) << std::endl;
return 0;
}
上面的代码与 gcc 4.8.1 完全一样,但是当我尝试用 gcc 4.7.2 编译它时,我得到以下信息:
$ g++ -std=c++11 -o test test_hash.cpp
test_hash.cpp:22:8: error: redefinition of ‘struct std::hash<_Tp>’
In file included from /usr/include/c++/4.7/functional:59:0,
from test_hash.cpp:1:
/usr/include/c++/4.7/bits/functional_hash.h:58:12: error: previous definition of ‘struct std::hash<_Tp>’
/usr/include/c++/4.7/bits/functional_hash.h: In instantiation of ‘struct std::hash<Derived>’:
test_hash.cpp:31:24: required from here
/usr/include/c++/4.7/bits/functional_hash.h:60:7: error: static assertion failed: std::hash is not specialized for this type
任何人都可以想出一种方法来使 std::hash 的这种特化适用于使用 gcc 4.7.2 从 Hashable 派生的任何类吗?
【问题讨论】:
-
呃不,代码被破坏了。您不能在
std中声明新模板。您只能在特定条件下编写现有模板的特化。你所拥有的不是专业 -
即使我们忽略了关于你在 std 命名空间中做什么和不被允许做什么的规则,你的类是一个重新定义,在任何上下文中都是不允许的,即使它被允许,使用它将是模棱两可的,因为两个定义都会匹配。您将不得不专门针对每种类型或仅针对
Hashable,并且只需将std::hash<Hashable>用于它的所有派生类型。这就是为什么我不喜欢模板之类的特征而不喜欢通过 adl 实现的功能。 -
感谢您的 cmets。我怀疑我的解决方案不是很干净,实际上我很惊讶它在 gcc 4.8.1 中完全有效。我决定为每个派生类编写单独的特化。
标签: c++11 gcc hash template-specialization stdhash