Reputation: 85
What is this syntax Prof. Stroustrup uses in his book The C++ Programming Language 4th ed. while describing hash and equality functions on page 917.
std::hash<int>{}(variable) //variable is of type int
Is that a casting from int to hash ? But why those flower brackets after hash? I know that placing them after a variable default initializes it. As for as casting is concerned we normally cast like say double (int)!
Upvotes: 3
Views: 651
Reputation: 409136
Lets break std::hash<int>{}(variable)
down into its components:
std::hash<int>
- This is the type, it's a specific type of standard hash template.
{}
- This creates an instance of the std::hash<int>
class.
(variable)
- This calls the function call operator on the instance previously created, passing variable
as argument.
After the expression, the instance of the std::hash<int>
object is destructed.
For example:
std::size_t hash = std::hash<int>{}(variable);
is roughly equivalent to
std::size_t hash;
{
std::hash<int> hashing_temporary_object;
hash = hashing_temporary_object(variable);
// The above call is equal to hashing_temporary_object.operator()(variable)
}
Upvotes: 8
Reputation: 72271
std::hash
is a class template. <int>
provides template arguments to the template. std::hash<int>
together is the type produced by a specialization of the class template. std::hash<int>{}
default-constructs a value of that type. std::hash<int>{}(variable)
calls the class's operator()
to evaluate the hash for a given number.
Upvotes: 1
Reputation: 19232
std::hash<int>{}
creates a function object.
As you say the "flowery" or even curly braces initialise this.
You then call the function with the int
.
Upvotes: 0