Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::type_info::hash_code

      From cppreference.com
      <cpp‎ |types‎ |type info
       
       
      Utilities library
       
       
       
      std::size_t hash_code()constnoexcept;
      (since C++11)

      Returns an unspecified value (here denoted byhash code) such that for allstd::type_info objects referring to the same type, theirhash code is the same.

      No other guarantees are given:std::type_info objects referring to different types may have the samehash code (although the standard recommends that implementations avoid this as much as possible), andhash code for the same type can change between invocations of the same program.

      Contents

      [edit]Parameters

      (none)

      [edit]Return value

      A value that is identical for allstd::type_info objects referring to the same type.

      [edit]Example

      The following program is an example of an efficient type-value mapping without usingstd::type_index.

      Run this code
      #include <functional>#include <iostream>#include <memory>#include <string>#include <typeinfo>#include <unordered_map> struct A{virtual ~A(){}}; struct B: A{};struct C: A{}; using TypeInfoRef=std::reference_wrapper<conststd::type_info>; struct Hasher{std::size_t operator()(TypeInfoRef code)const{return code.get().hash_code();}}; struct EqualTo{bool operator()(TypeInfoRef lhs, TypeInfoRef rhs)const{return lhs.get()== rhs.get();}}; int main(){std::unordered_map<TypeInfoRef,std::string, Hasher, EqualTo> type_names;     type_names[typeid(int)]="int";    type_names[typeid(double)]="double";    type_names[typeid(A)]="A";    type_names[typeid(B)]="B";    type_names[typeid(C)]="C"; int i;double d;    A a; // note that we're storing pointer to type Astd::unique_ptr<A> b(new B);std::unique_ptr<A> c(new C); std::cout<<"i is "<< type_names[typeid(i)]<<'\n';std::cout<<"d is "<< type_names[typeid(d)]<<'\n';std::cout<<"a is "<< type_names[typeid(a)]<<'\n';std::cout<<"*b is "<< type_names[typeid(*b)]<<'\n';std::cout<<"*c is "<< type_names[typeid(*c)]<<'\n';}

      Output:

      i is intd is doublea is A*b is B*c is C

      [edit]See also

      (removed in C++20)
      checks whether the objects refer to the same type
      (public member function)[edit]
      implementation defined name of the type
      (public member function)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/types/type_info/hash_code&oldid=168467"

      [8]ページ先頭

      ©2009-2025 Movatter.jp