Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 726
Corey Taylor Avatar asked Sep 13 '17 15:09

Corey Taylor


2 Answers

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
like image 139
Yakk - Adam Nevraumont Avatar answered Sep 20 '22 22:09

Yakk - Adam Nevraumont


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().

enter image description here

like image 29
463035818_is_not_a_number Avatar answered Sep 20 '22 22:09

463035818_is_not_a_number