我正在为pair < int,int >
键创建哈希函数。
无论如何,我发现以下使用std::hash<>
的实现:
typedef struct hasher_t {
template <class T1, class T2>
size_t operator()(const pair<T1,T2>& key) const {
//standard hasher for T1, T2
auto h1 = std::hash<T1>()(key.first); //also possible
auto h2 = std::hash<T2>()(key.second); //also possible
/*
auto h1 = std::hash<T1>{}(key.first);
auto h2 = std::hash<T2>{}(key.second);
*/
return h1 ^ (h2 - 1);
}
} hasher;
std::hash<T1>()
和std::hash<T1>{}
都可以,但是我不知道为什么可以。我什至找不到相关的引用文章。
我猜他们都为
std::hash<T1>
类做了字面上的“未命名的时间实例”,并调用了operator()(T1)
方法。这样对吗?
最佳答案
是的,都可以构造临时std::hash
,然后在临时对象上调用operator()
。std::hash<T1>()
执行value initialization,
1,5) when a nameless temporary object is created with the initializer consisting of an empty pair of parentheses
or braces (since C++11)
;
临时由默认构造函数初始化。
std::hash<T1>{}
执行list initialization(自C++ 11起),2) initialization of an unnamed temporary with a braced-init-list
效果是,默认构造函数的临时属性也为value-initialized。
关于c++ - 语法使未命名实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62059640/