【发布时间】:2016-05-19 03:13:26
【问题描述】:
通常,如果新类型需要哈希,则必须专门化 std::hash。我编写了一个测试哈希库,并希望将它用于标准库尚未专门化的所有类型。
我使用 gcc/4.9.3 和 clang/3.7.0 尝试了以下操作。令我惊讶的是,它确实有效。
#include <utility>
#include <functional>
#include <iostream>
namespace std {
template<typename T>
class hash
{
public:
size_t operator()(const T & obj)
{
return 99;
}
};
}
int main(void)
{
int i = 10;
std::pair<int, int> pi{22,33};
std::hash<int> hi;
std::hash<std::pair<int, int>> hpi;
std::cout << "Hash of int: " << hi(i) << "\n";
std::cout << "Hash of int pair: " << hpi(pi) << "\n";
return 0;
}
整数的哈希是整数本身(这是标准库版本),对的哈希是99。
那么两个问题。
为什么有效?
std::hash的模板版本应该已经被声明了。 (我唯一的猜测是它在更深的命名空间中,会被转发)这是标准行为吗?
编辑:对问题 1 的回答 - 已声明 template<typename T> struct hash,但似乎未在任何地方定义。这就是为什么我可以定义它。
【问题讨论】:
-
像往常一样,未定义的行为包括“似乎在工作”。
-
@T.C.因此想知道这是否是已定义的行为......