C++ `typeid` Operator

smsh0722·2일 전

기타 정리

목록 보기
5/7

C++ typeid Operator

typeid는 객체나 표현식의 Type Information (타입 정보)을 얻는 연산자이다.

#include <typeinfo>

typeid(expression)
typeid(type)

반환값은 std::type_info 객체이다.

주요 기능

타입 비교

int a;
double b;

typeid(a) == typeid(int);    // true
typeid(a) == typeid(b);      // false

타입 이름 확인

cout << typeid(a).name();

name()의 결과는 Implementation-Defined (구현체 의존적)이므로 컴파일러마다 다를 수 있다.

Static Type vs Dynamic Type

class Base {
public:
    virtual ~Base() = default;
};

class Derived : public Base {};

int main( void )
{
  Derived d;
  Base* p = &d;

  typeid(p);   // Base*
  typeid(*p);  // Derived
}

Base가 Polymorphic Class (다형 클래스)이면 typeid(*p)는 실제 객체의 Dynamic Type (동적 타입)을 확인한다.

virtual 함수가 없다면 실제 객체가 Derived여도 Static Type (정적 타입)인 Base로 판단한다.

nullptr 주의

Base* p = nullptr;
typeid(*p);

다형 클래스의 null 포인터를 역참조하면 std::bad_typeid 예외가 발생한다.

핵심 정리

  • typeid(x) → 타입 정보 확인
  • typeid(x) == typeid(T) → 타입 비교
  • .name() → 타입 이름 확인
  • Polymorphic (다형) 객체 → 실제 Runtime Type 확인 가능
  • 일반 객체 → Static Type 기준
  • 반환 타입 → std::type_info

0개의 댓글