std::hash<std::variant>
From cppreference.com
C++
Feature test macros (C++20)
Concepts library (C++20)
Metaprogramming library (C++11)
Ranges library (C++20)
Filesystem library (C++17)
Concurrency support library (C++11)
Execution control library (C++26)
Utilities library
Type support (basic types, RTTI)
Library feature-test macros (C++20)
(C++11)
(C++20)
(C++26)
(C++20)
Coroutine support (C++20)
Contract support (C++26)
(C++20)(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
General utilities
Relational operators (deprecated in C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
(C++20)
Swap and type operations
Common vocabulary types
std::variant
(C++26)
hash<std::variant>
Defined in header
<variant>
template< class... Types >
struct hash<std::variant <Types...>>;
(since C++17)
struct hash<std::variant <Types...>>;
The template specialization of std::hash for the std::variant template allows users to obtain hashes of variant
objects.
The specialization std::hash
<std::variant <Types...>> is enabled (see std::hash ) if every specialization in std::hash
<std::remove_const_t <Types>>... is enabled, and is disabled otherwise.
The member functions of this specialization are not guaranteed to be noexcept.
Contents
[edit] Template parameters
Types
-
the types of the alternatives supported by the
variant
object
[edit] Notes
Unlike std::hash<std::optional>, hash of a variant does not typically equal the hash of the contained value; this makes it possible to distinguish std::variant <int, int> holding the same value as different alternatives.
[edit] Example
Run this code
#include <iostream> #include <string> #include <variant> using Var = std::variant <int, int, int, std::string >; template<unsigned I> void print(Var const& var) { std::cout << "get<" << var.index() << "> = " << std::get<I>(var) << "\t" "# = " << std::hash <Var>{}(var) << '\n'; } int main() { Var var; std::get<0>(var) = 2020; print<0>(var); var.emplace<1>(2023); print<1>(var); var.emplace<2>(2026); print<2>(var); var = "C++"; print<3>(var); }
Possible output:
get<0> = 2020 # = 2020 get<1> = 2023 # = 2024 get<2> = 2026 # = 2028 get<3> = C++ # = 15518724754199266859