6

In C++11, it is possible to get a hashed value for a string variable as follows:

std::size_t h1 = std::hash<std::string>{}("Some_String");

It is clean and simple. However, I have two questions:

  1. Why do we need the curly braces here?
  2. Is it possible to escape using the braces?
MTMD
  • 1,162
  • 2
  • 11
  • 23
  • 1
    Possible duplicate of [What are the differences between C-like, constructor, and uniform initialization?](https://stackoverflow.com/questions/24953658/what-are-the-differences-between-c-like-constructor-and-uniform-initialization) –  Oct 19 '18 at 02:55
  • Note that `std::hash` instances are _types_, not functions. This, e.g., allows to specialize `std::hash` for user-defined types in the `std` namespace, which will no longer be allowed for _template functions_ in C++20. – Daniel Langr Oct 19 '18 at 06:40

1 Answers1

10

The curly braces are used to value-initialize an object of type std::hash<std::string>. That object can then be called, since it has an overloaded operator(). Alternatively, you could create a named object:

std::hash<std::string> H;
auto h1 = H("Some_String");
Brian Bi
  • 111,498
  • 10
  • 176
  • 312