std::hash<std::variant>

Header: <variant>

The template specialization of std::hash for the std::variant template allows users to obtain hashes of variant objects.

# Declarations

template< class... Types >
struct hash<std::variant<Types...>>;

(since C++17)

# Notes

Unlike std::hashstd::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.

# Example

#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);
}

# See also