[英]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: 有多种原因,每种原因都足以满足选择:
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). 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.