반응형
  • typeid
    • 타입에 대한 정보를 얻을때 사용하는 연산자
    • <typeinfo> 헤더 파일을 포함해야 함 // 컴파일러에 따라 생략 가능(표준 스팩은 명시 해야함)
    • typeid(타입)
    • typeid(객체)
    • typeid(expression)
    • typeid의 결과로 const std::type_info& 반환
    • 가상 함수가 없는 객체(non-polymorphic) : 컴파일 시간에 타입 조사
    • 가상 함수가 있는 객체(polymorphic) : 실행시간에 타입을 조사(가상함수 테이블 정보 참고)
  • std::type_info
    • 타입의 정보를 담고 있는 클래스
    • 사용자가 직접 객체 생성할 수 없고 typeid() 연산자를 통해서만 얻을 수 있음
    • 멤버 함수인 name()을 통해서 타입의 이름을 얻을 수 있음
    • 실행 결과는 컴파일러 마다 표현 바법이 다름
    • g++로 생성된 실행파일의 경우 "a.exe | c++filt -t"로 실행하면 완전한 타입의 이름을 볼수 있음
  • RTTI(Run Time Type Information)
    • 실행 시간에 타입의 정보를 조사하는 기법
  • std::type_info로 동일 타입 조사 방법
    • t1 == t2 : ok
    • t1.hash_code() == t2.hash_code() : ok
    • std::type_index(t1) == std::type_index(t2) : ok
    • &t1 == &t2 : not guaranteed
#include <iostream>
#include <typeinfo>
#include <typeindex>

class Animal 
{
public:
    virtual ~Animal() {}

};
class Dog : public Animal {};

void foo(Animal* p)
{
    const type_info& t1 = typeid(*p);
    const type_info& t2 = typeid(Dog);

    // 방법 1
    if (t1 == t2) // 실전 코드 : if( typeid(*p) == typeid(Dog))
    {
        std::cout << "p는 Dog" << std::endl;
    }
    // 방법 2
    if (t1.hash_code() == t2.hash_code())
    {

    }
    // 방법 3
    if (std::type_index(t1) == std::type_index(t2))
    {

    }

    std::cout << t1.name() << std::endl;
}

int main()
{
    Animal a; foo(&a);
    Dog d; foo(&d);
}

 

 

반응형

+ Recent posts