4 ms·
>For example if you have a nested class that you want to use in an unordered_set in its parent class then you just can’t do it because you can’t put the std::ha
by Kranar 1y ago
>For example if you have a nested class that you want to use in an unordered_set in its parent class then you just can’t do it because you can’t put the std::hash specialization anywhere legal.
This is not true. From within your parent class you use an explicit hashing callable, and then from outside of the parent class you can go back to using the default std::hash.
The result looks like this:
struct Foo {
struct Bar {};
struct BarHasher {
std::size_t operator ()(const Bar&) const noexcept;
};
std::unordered_set<Bar, BarHasher> bar_set;
};
namespace std {
template<>
struct hash<Foo::Bar> {
std::size_t operator()(const Foo::Bar& b) const noexcept {
return Foo::BarHasher()(b);
}
};
}
The std::hash specialization at the end is legal and allows other users of Foo::Bar to use std::unordered_set<Foo::Bar> without needing the explicit BarHasher.