gpt4 book ai didi

c++ - 重新定义 std::hash 模板结构

转载 作者:行者123 更新时间:2023-11-28 05:40:05 29 4
gpt4 key购买 nike

通常,如果新类型需要散列,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。

那么两个问题。

  1. 为什么有效? std::hash 的模板化版本应该已经声明了。 (我唯一的猜测是它在更深的命名空间中,被转发)

  2. 这是标准行为吗?

编辑:问题 1 的答案 - template<typename T> struct hash已声明,但似乎未在任何地方定义。这就是为什么我可以定义它。

最佳答案

17.6.4.2.1 Namespace std [namespace.std]

1 The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified. A program may add a template specialization for any standard library template to namespace std only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited.

由于您将已存在的通用模板重新定义为 namespace std,因此您具有未定义的行为。这包括@T.C。在评论中提到,该程序运行良好。

关于c++ - 重新定义 std::hash 模板结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37306477/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com