RTTI - Gakgu/Gakgu.github.io GitHub Wiki

개요

Run-Time Type Information. 실시간 타입 정보다. 실행 중 타입 정보가 필요할 때 사용한다. 컴파일러에서 RTTI기능을 수동으로 켜야하는 경우가 있다.

typeid 연산자

Header

#include <typeinfo>

return type

class type_info {
  ...
  public:
    const char* name() const;
    const char* raw_name() const;
    int operator==(const type_info& rhs) const;
    int operator!=(const type_info& rhs) const;
  ...
};

사용법

typeid(변수).name();
typeid(변수).raw_name();

GCC 리턴값

결과물은 컴파일러마다 다르며 여기 예제에서는 gcc기반의 결과물을 알아본다.

기본 타입

타입의 첫 알파벳만 리턴
ex) typeid(int).name()일 경우 i 리턴

클래스

클래스 이름의 개수 + 클래스의 이름
ex) typeid(class gakgu)name()일 경우 5gakgu 리턴

포인터

P + 원래 타입의 리턴값
ex) typeid(class gakgu*).name()일 경우 P5gakgu 리턴

결론

컴파일러마다 결과값이 다르므로 typeid를 사용할 때에는 class type_info의 비교 연산자만 사용한다.

if(typeid(int) == type(char))
  ...;
⚠️ **GitHub.com Fallback** ⚠️