为什么std :: hash是一个结构而不是一个函数? [英] Why is std::hash a struct instead of a function?

查看:193
本文介绍了为什么std :: hash是一个结构而不是一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标准库将std :: hash实现为专用于不同类型的模板结构。它的使用方式如下:

Standard library implements std::hash as a template struct that is specialized for different types. 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. 你可以部分地专门化类模板,但你只能完全专门的函数模板远)。因此,您可以为整个相关模板参数提供替换, std :: hash< T> 是类模板。注意,部分重载没有帮助,因为散列函数需要以某种方式指定为一个对象,而这个对象不能用重载函数来完成(除非它们通过对象访问,但这是对象)。

  2. 无序的关联容器用静态实体(如果特定类型支持的话,也可以动态定制)进行参数化,这使用类模板更容易完成。

  3. 由于用于哈希函数的条目是可定制的,所以可以在使用类型或函数指针进行定制之间进行选择。函数指针通常难以内联,而类型的内联成员函数对于内联是微不足道的,提高了简单函数的性能,例如计算一个简单的哈希。

  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. 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 associatiative 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 enties 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.

这篇关于为什么std :: hash是一个结构而不是一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆