dynamic_castの有効性の問題
3639 ワード
/********************************************************************
file name : CLK.h
author : Clark/
created : 2011-12-12
purpose : dynamic_cast
dynamic_cast [ , ]
*********************************************************************/
#include <iostream>
using namespace std;
#define DECLARE_CLASS_CREATE(class_name) static char* getName() { return #class_name; };
template<class T_TYPE>
class T2T
{
public:
typedef T_TYPE CUR_TYPE;
};
class Root
{
public:
DECLARE_CLASS_CREATE(Root)
virtual void show(){}
};
class Root_1Ex:public Root
{
public:
DECLARE_CLASS_CREATE(Root_1Ex)
};
class Root_1Ex_1Ex:public Root_1Ex
{
public:
DECLARE_CLASS_CREATE(Root_1Ex_1Ex)
};
class Root_2Ex:public Root
{
public:
DECLARE_CLASS_CREATE(Root_2Ex)
};
template<class T_Base, class T_Ex, class T_Test>
void Test_Dynamic_Cast(T_Base obj1, T_Ex obj2, T_Test obj3)
{
cout<<"-----------------------------------------------------------"<<endl;
T_Base::CUR_TYPE* pBase = new T_Ex::CUR_TYPE();
if( NULL != pBase)
{
cout<<"Succeed: "<<T_Base::CUR_TYPE::getName()<<" = new "<< T_Ex::CUR_TYPE::getName()<<endl;
}
else
{
cout<<"Failed: "<<T_Base::CUR_TYPE::getName()<<" = new "<< T_Ex::CUR_TYPE::getName()<<endl;
}
T_Test::CUR_TYPE* pTest = dynamic_cast<T_Test::CUR_TYPE*>(pBase);
if( NULL != pTest)
{
cout<<"Succeed: "<<"dynamic_cast<"<< T_Test::CUR_TYPE::getName()<<"*>("<<T_Base::CUR_TYPE::getName()<<")"<<endl;
}
else
{
cout<<"Failed: "<<"dynamic_cast<"<< T_Test::CUR_TYPE::getName()<<"*>("<<T_Base::CUR_TYPE::getName()<<")"<<endl;
}
cout<<"-----------------------------------------------------------"<<endl;
cout<<endl;
}
void main()
{
Test_Dynamic_Cast(T2T<Root>(), T2T<Root_1Ex>(), T2T<Root_1Ex>());
Test_Dynamic_Cast(T2T<Root>(), T2T<Root_1Ex>(), T2T<Root_1Ex_1Ex>());
Test_Dynamic_Cast(T2T<Root>(), T2T<Root_1Ex>(), T2T<Root_2Ex>());
Test_Dynamic_Cast(T2T<Root>(), T2T<Root_1Ex_1Ex>(), T2T<Root_1Ex>());
system("pause");
}
実行結果:
----------------------------------------------------------- Succeed: Root = new Root_1Ex Succeed: dynamic_cast
----------------------------------------------------------- Succeed: Root = new Root_1Ex Failed: dynamic_cast
----------------------------------------------------------- Succeed: Root = new Root_1Ex Failed: dynamic_cast
----------------------------------------------------------- Succeed: Root = new Root_1Ex_1Ex Succeed: dynamic_cast