Skip to content

Instantly share code, notes, and snippets.

@miss-programgamer
Created December 20, 2025 01:18
Show Gist options
  • Select an option

  • Save miss-programgamer/aa416857f01c33835dc43a32fdc640b0 to your computer and use it in GitHub Desktop.

Select an option

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).
#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