7.31(화) C++ - typeid, type_info

from Study/C++ 2007/08/02 15:29 view 18868

#include <iostream>

#include <typeinfo.h>
using
namespace std;
 

// template에서instatiation type을알아보는방법

// const T& char const[6] 그러므로문자열의길이가다르다면에러!!

// T char const* 으로타입이결정된다.

// 그러므로타입을정할때조심해서정해야한다.!!!

template<typename T> void foo( T a, T b )

{

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

}


template<typename T> void goo( const T& a, const T& b )

{

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

}


void main()

{

        foo( "hello", "hel" );

        goo( "hello", "hello" );

        //goo( "hello", "hel" ); // error
}

 

///////////////////////////////////////////////////////////////////
// RTTI : Run Time Type Information

class A

{

public:

        virtual ~A() {}               // 상속이라면100% 가상함수를쓰게된다.

};

 

void foo( B* p )

{

}

 

class B : public A

{

public:

};

 

void foo( A* p )

{

        // 여기서pA인지B인지를알고싶다면!!

        // B* pp = (B*)p; // error A가넘어오게되면undefine??

 

        // 방법1. typeid() 연산자사용

        const type_info& t = typeid(*p); // 6.0에서는\GR 옵션을줘야한다.

        cout << t.name() << endl; // 가상함수가있어야제대로동작한다(소멸자라도추가)

 

        if ( typeid(*p) == typeid(B) )

        {

               B* pp = (B*)p; // 안전하다.

        }

 

        // 방법2. 이거만하도록나온dynamic_cast. DYNAMIC_CAST() <-- MFC

        B* p2 = dynamic_cast<B*>(p);  // down cast 가발생하면0이리턴된다.

        if ( p2 != 0 )

        {

               // p2사용

        }

}

 

void main()

{

        B b;

 

        foo( &b );

}

 

Tag |

Trackback Address :: 이 글에는 트랙백을 보낼 수 없습니다