Why is {} used to access operator() in std::hash?

安稳与你 提交于 2019-12-22 06:46:51

问题


While reading the examples of std::hash used for std::unordered_map, I noticed that the operator() function was being accessed by {}.

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)
}

What does the use of {} here represent?


回答1:


std::hash<T> is a type not a function.

An instance of std::hash has an operator() that does the hash.

So std::hash<std::string> is a hashing type. {} then creates an instance of that type. (s.first_name) calls operator() on a std::hash<std::string>.

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



回答2:


std::hash is not a function, but a class, more specifically a functor. So you have to create an object of that class before you can call its operator().



来源:https://stackoverflow.com/questions/46201224/why-is-used-to-access-operator-in-stdhash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!