c++ functor usage, e.g. std::hash

发布时间:2023年12月27日

This line :

size_t hashVal0 = std::hash<std::string>{}(strInput);

equal these two lines:? ?

std::hash<std::string> szHash;
?size_t hashVal = szHash(strInput);
?

The?hashVal0 ==?hashVal == true.

this is why need {} in first line:

  • std::hash<KeyType>{}: This creates an instance of the?std::hash<KeyType>?class. The?{}?is used to call the default constructor.
  • (key): This calls the?operator()?method on the instance of?std::hash<KeyType>, passing?key?as the argument.

more deep dive:

The syntax?std::hash<KeyType>(key)?might look like it’s invoking a function, but?std::hash<KeyType>?is not a function—it’s a class template. Therefore,?std::hash<KeyType>(key)?would be trying to call a constructor of?std::hash<KeyType>?that takes an argument of type?KeyType, but no such constructor exists.

文章来源:https://blog.csdn.net/raidtest/article/details/135255095
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。