types_type_index

types_type_index (타입 인덱스)

이 페이지는 C++ 표준 라이브러리의 type_index 클래스에 대해 설명해요. type_indexstd::type_info 객체를 감싸는 래퍼 클래스로, 연관 컨테이너와 비정렬 연관 컨테이너에서 인덱스로 사용할 수 있어요. 내부적으로 type_info 객체를 포인터로 참조하기 때문에 복사 생성과 복사 할당이 가능해요.

출처: cppreference

본문

개요

헤더 <typeindex>에 정의되어 있어요. (since C++11)

type_index 클래스는 std::type_info 객체를 감싸는 래퍼 클래스예요. 이 클래스는 연관 컨테이너(associative container)와 비정렬 연관 컨테이너(unordered associative container)에서 인덱스로 사용할 수 있어요. type_info 객체와의 관계는 포인터를 통해 유지되므로, type_index는 복사 생성 가능(CopyConstructible)하고 복사 할당 가능(CopyAssignable)해요.

멤버 함수

멤버 함수 설명
(constructor) 객체를 생성해요 (public member function)
(destructor) (암시적으로 선언됨) type_index 객체를 소멸해요 (public member function)
operator= (암시적으로 선언됨) type_index 객체를 할당해요 (public member function)
operator==, operator!=, operator<, operator<=, operator>, operator>= (C++20에서 제거됨), operator<=> (C++20) 내부의 std::type_index 객체들을 비교해요 (public member function)
hash_code 해시 코드를 반환해요 (public member function)
name 내부의 type_info 객체와 연관된 타입의 구현 정의 이름을 반환해요 (public member function)

헬퍼 클래스

헬퍼 클래스 설명
std::hash<std::type_index> (C++11) 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

같이 보기

관련 항목 설명
type_info 타입에 대한 정보를 포함하는 클래스로, typeid 연산자가 반환하는 클래스예요 (클래스)
typeid 타입의 정보를 조회하며, 해당 타입을 나타내는 std::type_info 객체를 반환해요 (내장 연산자)

더 알아보기 (Learn more)

cppreference