Created
December 20, 2025 01:18
-
-
Save miss-programgamer/aa416857f01c33835dc43a32fdc640b0 to your computer and use it in GitHub Desktop.
An implementation of a dictionary type in C++ as an alias of std::unordered_map which uses a custom hash functor. This hash uses a trait type to tag specific combinations of types as transparent so that map lookups can happen using heterogenous types (like std::string and std::string_view, for instance).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <string> | |
| #include <string_view> | |
| #include <unordered_map> | |
| template<typename T, typename = void> | |
| struct KeyTraits {}; | |
| template<> | |
| struct KeyTraits<std::string, std::string_view> | |
| { | |
| using IsTransparent = void; | |
| }; | |
| template<typename O, typename T> | |
| concept TransparentTo = requires | |
| { | |
| typename KeyTraits<T, O>::IsTransparent; | |
| }; | |
| template<typename T> | |
| struct KeyHash : public std::hash<T> | |
| { | |
| using is_transparent = void; | |
| template<TransparentTo<T> O> | |
| static constexpr size_t operator()(const O& other) | |
| { return std::hash<O>{}(other); } | |
| }; | |
| template<typename K, typename T, typename A = std::allocator<std::pair<const K, T>>> | |
| using Dictionary = std::unordered_map<K, T, KeyHash<K>, std::equal_to<void>>; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment