Added InheritTest.cpp

This commit is contained in:
hyzboy 2025-01-09 00:43:37 +08:00
parent ddf1bb4d0f
commit c19c034b31
2 changed files with 71 additions and 0 deletions

View File

@ -39,6 +39,7 @@ cm_example_project("DataType/TypeInfo" TypeSizeof datatype/TypeInfo/Ty
cm_example_project("DataType/TypeInfo" TypeCastTest datatype/TypeInfo/TypeCastTest.cpp) cm_example_project("DataType/TypeInfo" TypeCastTest datatype/TypeInfo/TypeCastTest.cpp)
cm_example_project("DataType/TypeInfo" TypeCheck datatype/TypeInfo/TypeCheck.cpp) cm_example_project("DataType/TypeInfo" TypeCheck datatype/TypeInfo/TypeCheck.cpp)
cm_example_project("DataType/TypeInfo" ObjectRelationTest datatype/TypeInfo/ObjectRelationTest.cpp) cm_example_project("DataType/TypeInfo" ObjectRelationTest datatype/TypeInfo/ObjectRelationTest.cpp)
cm_example_project("DataType/TypeInfo" InheritTest datatype/TypeInfo/InheritTest.cpp)
#################################################################################################### ####################################################################################################
cm_example_project("DataType" HalfFloatTest datatype/HalfFloatTest.cpp) cm_example_project("DataType" HalfFloatTest datatype/HalfFloatTest.cpp)

View File

@ -0,0 +1,70 @@
#include<typeinfo>
#include<iostream>
class Object
{
public:
virtual size_t GetTypeHash()const noexcept=0;
virtual const char *GetTypeName()const noexcept=0;
};
template<typename T,typename BASE> class Inherit:public BASE
{
public:
static const size_t StaticHash()noexcept
{
return typeid(T).hash_code();
}
virtual size_t GetTypeHash()const noexcept override
{
return T::StaticHash();
}
static const char *StaticName()noexcept
{
return typeid(T).name();
}
virtual const char *GetTypeName()const noexcept override
{
return T::StaticName();
}
};//template<typename T> class Inherit:public T
class TestClass:public Inherit<TestClass,Object>
{
};
class TestClassA:public Inherit<TestClassA,TestClass>
{
};
class TestClassB:public Inherit<TestClassB,TestClass>
{
};
template<typename T> void out(const char *name,T *obj)
{
std::cout<<name<<" static "<<T::StaticName()<<": "<<std::hex<<T::StaticHash()<<std::endl;
std::cout<<name<<" dynamic "<<obj->GetTypeName()<<": "<<std::hex<<obj->GetTypeHash()<<std::endl;
}
int main(int,char **)
{
TestClass tc;
TestClassA ta;
TestClassB tb;
out("tc",&tc);
out("ta",&ta);
out("tb",&tb);
out<TestClass>("ta",&ta);
out<TestClass>("tb",&tb);
return 0;
}