Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::hash<std::variant>

      From cppreference.com
      <cpp‎ |utility‎ |variant
       
       
      Utilities library
       
       
      Defined in header<variant>
      template<class...Types>
      struct hash<std::variant<Types...>>;
      (since C++17)

      The template specialization ofstd::hash for thestd::variant template allows users to obtain hashes ofvariant objects.

      The specializationstd::hash<std::variant<Types...>> is enabled (seestd::hash) if every specialization instd::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 thevariant object

      [edit]Notes

      Unlikestd::hash<std::optional>, hash of a variant does not typically equal the hash of the contained value; this makes it possible to distinguishstd::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(Varconst& 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   # = 2020get<1> = 2023   # = 2024get<2> = 2026   # = 2028get<3> = C++    # = 15518724754199266859

      [edit]See also

      (C++11)
      hash function object
      (class template)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/utility/variant/hash&oldid=149609"

      [8]ページ先頭

      ©2009-2025 Movatter.jp