1.定义
结合前面的内容,可以定义如下的基类
1 class Object : public Memory 2 { 3 DECL_TPLT(Object); 4 DECL_RTTI(Object); 5 public: 6 bool isKindOf(me::Type type) const 7 { 8 return getType().isKindOf(type); 9 } 10 bool isExactKindOf(me::Type type) const 11 { 12 return getType().isExactKindOf(type); 13 } 14 const char* getTypeName()const 15 { 16 return getType().getName(); 17 } 18 };
定义继承类型
class DerivedObject : public me::Object { DECL_TPLT(DerivedObject); DECL_RTTI(DerivedObject, Object); }; template <typename T> class TemplateObject : public DerivedObject { DECL_TPLT(TemplateObject, T); DECL_RTTI(TemplateObject, DerivedObject); };
2.使用
1 DerivedObject* pdo1 = new DerivedObject(); 2 Object* po1 = pdo1->getType().newObject(); 3 if (pdo1->getType() == pdo1->getType()) { 4 std::cout << "po1 is an instance of " << po1->getType().getName() << std::endl; 5 DerivedObject* pdo2 = static_cast<DerivedObject*>(po1); 6 } 7 typedef TemplateObject<Object*> TObject; 8 Type tobj = TObject::TypeId; 9 std::cout << tobj.getName() << ":" << tobj.getHash() << std::endl; 10 Type btdobj = tobj.getBaseTypes()[0]; 11 std::cout << btdobj.getName() << ":" << btdobj.getHash() << std::endl; 12 Type tbase = Object::TypeId; 13 if (tobj.isKindOf(tbase)) { 14 std::cout << tobj.getName() << " is kind of " << tbase.getName(); 15 } 16 delete pdo1;
3.结果
时间: 2024-12-15 06:54:14