How do I use heterogeneous lookup with std::unordered_map?

In C++, heterogeneous lookup using `std::unordered_map` allows for more flexibility in key types by leveraging type erasure to access different types of keys using a consistent interface. This means you can easily look up or access values associated with keys of different types.

Here’s a simple example demonstrating heterogeneous lookup with `std::unordered_map`:

#include <iostream> #include <unordered_map> #include <string> #include <variant> using KeyType = std::variant<int, std::string>; struct KeyHasher { std::size_t operator()(const KeyType& key) const { return std::visit([](const auto& k) { return std::hash<std::decay_t<decltype(k)>>{}(k); }, key); } }; struct KeyEqual { bool operator()(const KeyType& lhs, const KeyType& rhs) const { return lhs == rhs; } }; int main() { std::unordered_map<KeyType, std::string, KeyHasher, KeyEqual> my_map; // Insert values my_map[42] = "Answer to life"; my_map[std::string("hello")] = "Greeting"; // Access values std::cout << std::get<std::string>(my_map[std::string("hello")]) << std::endl; // Output: Greeting std::cout << my_map[42] << std::endl; // Output: Answer to life return 0; }

C++ heterogeneous lookup std::unordered_map type erasure key types C++ map example