简体   繁体   English

为什么std :: hash是一个struct而不是一个函数?

[英]Why is std::hash a struct instead of a function?

Standard library implements std::hash as a template struct that is specialized for different types. 标准库将std :: hash实现为专门用于不同类型的模板结构。 It is used like this: 它是这样使用的:

#include <iostream>
#include <functional>

int main()
{
    std::hash<int> hasher;
    std::cout << hasher(1337) << std::endl;

    return 0;
}

My question is what is the reasoning behind this design choice. 我的问题是这种设计选择背后的原因是什么。 Why it isn't implemented as a template function and used like this: 为什么它没有实现为模板函数并像这样使用:

#include <iostream>
#include <functional>

int main()
{
    std::cout << std::hash<int>(1337) << std::endl;

    return 0;
}

There are, multiple reasons, each one good enough to just the choice: 有多种原因,每种原因都足以满足选择:

  1. You can partially specialize class templates but you can only fully specialized function templates (at least, so far). 您可以部分地专门化类模板,但是您只能使用完全专用的功能模板(至少到目前为止)。 Thus, you can provide a replacement for an entire suite of related template arguments with std::hash<T> being a class template. 因此,您可以使用std::hash<T>作为类模板来替换整个相关模板参数。 Note that, partial overloading doesn't help because the hash function would need to be specified somehow as an object which can't be done with overloaded functions (unless they are accessed via an object but that's what is differentiated against). 请注意,部分重载没有帮助,因为哈希函数需要以某种方式指定为无法通过重载函数完成的对象(除非它们是通过对象访问的,但这是区别对待的)。
  2. The unordered associative containers are parametersized with a static entity (which can also be customized dynamically if the specific type supports that) which is easier done using class templates. 无序关联容器使用静态实体进行参数化(如果特定类型支持,也可以动态自定义),使用类模板更容易完成。
  3. Since the entities used for the hash function are customizable, the choice is between using a type or a function pointer for customization. 由于用于散列函数的实体是可自定义的,因此可以选择使用类型或函数指针进行自定义。 Function pointers are often hard to inline while inline member functions of a type are trivial to inline, improving the performance for simple functions like computing a simple hash quite a bit. 函数指针通常难以内联,而类型的内联成员函数对于内联来说是微不足道的,从而提高了简单函数的性能,例如计算简单的散列。

A template function can not be partially specialized for types, while std::hash specialized for different types as a class template. 模板函数不能部分专用于类型,而std::hash专门针对不同类型作为类模板。

And, in this template class based way, you can do some meta programming such as accessing to return type and key type like below: 并且,在这种基于模板类的方式中,您可以执行一些元编程,例如访问返回类型和键类型,如下所示:

std::hash<X>::argument_type
std::hash<X>::result_type

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM