2017-09-13 39 views
3

在阅读用于std :: unordered_map的std :: hash示例时,我注意到operator()函数正在被{}访问。为什么{}用于访问std :: hash中的operator()?

http://en.cppreference.com/w/cpp/utility/hash

result_type operator()(argument_type const& s) const 
{ 
    result_type const h1 (std::hash<std::string>{}(s.first_name)); 
    result_type const h2 (std::hash<std::string>{}(s.last_name)); 
    return h1^(h2 << 1); // or use boost::hash_combine (see Discussion) 
} 

什么是使用{}在这里代表什么?

+0

https://stackoverflow.com/questions/18222926/why-is-list-initialization-using-curly-braces-better-than-the-alternatives –

+1

祝C++允许'静态操作者( )单曲。 –

+0

相关/ dupe:https://stackoverflow.com/questions/40024008/how-to-understand-two-pairs-of-parentheses-in-this-code-fragment – NathanOliver

回答

6

std::hash<T>是一种类型不是功能。

std::hash的一个实例有一个operator()做散列。

所以std::hash<std::string>是散列型。然后{}创建该类型的实例。 (s.first_name)std::hash<std::string>上致电operator()

std::hash<std::string>{}(s.first_name); 
^     ^ ^
|      | call operator() on that instance 
type of hasher  | 
       create an instance of that type 
+0

@erip如果我这样做,你会给我一个upvote吗?只是在开玩笑:P我实际上会画出类似的东西,但我太慢了 – user463035818

+1

@ tobi303如果您添加徒手画的红色圆圈,我会赞成。 – Yakk

+0

你是相当苛刻的,但我也没有动力做任何事情:P – user463035818

2

std::hash不是函数,而是类,更具体地说函子。所以你必须先创建该类的一个对象,然后才能调用它的operator()

enter image description here

+0

它真的是写意吗? :> –

+0

徒手画。可悲的是我没有说“如果”,所以我已经投票了。 ;)但是+1徒手画的红色圆圈。 – Yakk

相关问题