Namespaces
Variants

std:: type_index

From cppreference.net
Utilities library
헤더 파일에 정의됨 <typeindex>
class type_index ;
(C++11부터)

type_index 클래스는 연관 컨테이너와 비순차 연관 컨테이너에서 인덱스로 사용할 수 있는 std::type_info 객체를 감싸는 래퍼 클래스입니다. type_info 객체와의 관계는 포인터를 통해 유지되므로, type_index CopyConstructible CopyAssignable 요구 사항을 만족합니다.

목차

멤버 함수

객체를 생성합니다
(public member function)
(destructor)
(implicitly declared)
type_index 객체를 파괴합니다
(public member function)
operator=
(implicitly declared)
type_index 객체를 할당합니다
(public member function)
내부 std::type_index 객체들을 비교합니다
(public member function)
해시 코드를 반환합니다
(public member function)
구현 정의된 타입 이름을 반환합니다,
내부 type_info 객체와 연관되어 있습니다
(public member function)

헬퍼 클래스

std::type_index 에 대한 해시 지원
(클래스 템플릿 특수화)

예제

다음 프로그램은 효율적인 타입-값 매핑의 예시입니다.

#include <iostream>
#include <memory>
#include <string>
#include <typeindex>
#include <typeinfo>
#include <unordered_map>
struct A
{
    virtual ~A() {}
};
struct B : A {};
struct C : A {};
int main()
{
    std::unordered_map<std::type_index, std::string> type_names;
    type_names[std::type_index(typeid(int))] = "int";
    type_names[std::type_index(typeid(double))] = "double";
    type_names[std::type_index(typeid(A))] = "A";
    type_names[std::type_index(typeid(B))] = "B";
    type_names[std::type_index(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[std::type_index(typeid(i))] << '\n';
    std::cout << "d is " << type_names[std::type_index(typeid(d))] << '\n';
    std::cout << "a is " << type_names[std::type_index(typeid(a))] << '\n';
    std::cout << "*b is " << type_names[std::type_index(typeid(*b))] << '\n';
    std::cout << "*c is " << type_names[std::type_index(typeid(*c))] << '\n';
}

출력:

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

참고 항목

일부 타입의 정보를 포함하며, typeid 연산자가 반환하는 클래스
(클래스)