typeid Operatortypeid는 객체나 표현식의 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 (구현체 의존적)이므로 컴파일러마다 다를 수 있다.
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() → 타입 이름 확인std::type_info