Is there no standard hash for `std::filesystem::path`?

Since there is a std::filesystem::hash_value that's part of the standard, why doesn't this code compile without me having to supply my own std::hash?

Right, there is a fs::hash_value() but there is no specialization of std::hash<fs::path>, which is what you would need. That's why it doesn't compile. As to why the library provides the former function but not the latter, I'll quote from Billy O'Neal (implementer for MSVC's standard library):

Looks like a defect.

However, putting paths as keys in a hash table is almost certainly incorrect; you need to test for path equivalence in most such scenarios. That is, "/foo/bar/../baz" and "/foo/baz" are the same target but are not the same path. Similarly, "./bar" and "./bar" may be different paths, depending on the value of current_path in the first context vs. in the second.

If what you want is canonically unique paths, then simply std::unordered_set<fs::path> wouldn't do what you want anyway. So perhaps it failing to compile isn't a bad thing? I don't know enough about filesystem to say one way or the other.


Note that you, yourself, providing a specialization of std::hash for fs::path is not allowed - you can only add specializations to std for types you control. Types that will be called "program-defined types." fs::path is not a type you control, so you can't specialize std::hash for it.

Tags:

C++

Hash

C++17