Namespaces
Variants

std::type_info::hash_code

From ko.cppreference.net
 
 
Utilities library
General utilities
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)(C++20)(C++20)    
(C++20)
Swap and type operations
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)



 
 
 
std::size_t hash_code() const noexcept;
(since C++11)

지정되지 않은 값(여기서는 해시 코드라고 함)을 반환합니다. 이 값은 동일한 타입을 참조하는 모든 std::type_info 객체에 대해 동일한 해시 코드를 갖도록 보장됩니다.

다른 보장은 제공되지 않습니다: 서로 다른 타입을 참조하는 std::type_info 객체가 동일한 해시 코드를 가질 수 있으며(표준에서는 구현이 이러한 상황을 최대한 피할 것을 권장합니다), 동일한 타입에 대한 해시 코드는 동일한 프로그램의 실행 간에 변경될 수 있습니다.

매개변수

(없음)

반환값

동일한 타입을 참조하는 모든 std::type_info 객체에 대해 동일한 값.

예제

다음 프로그램은 std::type_index 를 사용하지 않고 효율적인 타입-값 매핑의 예시입니다.

#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<const std::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 A
    std::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';
}

출력:

i is int
d is double
a is A
*b is B
*c is C

참고 항목

(removed in C++20)
객체가 동일한 타입을 참조하는지 확인
(public member function)
구현 정의 타입 이름
(public member function)