#include <iostream>
#include <string>
class Type {
public:
Type(const std::string& type, const Type* baseType)
: m_typeName(type)
, m_baseType(baseType)
{}
std::string typeName() const { return m_typeName; }
const Type* baseType() const { return m_baseType; }
private:
const Type* m_baseType;
std::string m_typeName;
};
class Object {
public:
template<typename T>
static T* cast(Object* obj) {
if (obj == nullptr) {
return nullptr;
}
const Type* t = obj->type();
do {
std::cout << t->typeName() << std::endl;
if (t == T::m_type) {
return (T*)obj;
}
} while (t = t->baseType());
return nullptr;
}
protected:
virtual const Type* type() { return m_type; }
inline static const Type* m_type = new Type("Object", nullptr);
};
#define OBJECT(Derive, Base) \
protected: \
friend class Object; \
virtual const Type* type() { return m_type; } \
inline static const Type* m_type = new Type(#Derive, Base::m_type);
template <typename T>
T* object_cast(Object* obj) {
return Object::cast<T>(obj);
}
class A : public Object
{
OBJECT(A, Object)
public:
A() {}
};
class B : public A
{
OBJECT(B, A)
public:
B() {}
};
class C : public B
{
OBJECT(C, B)
public:
C() {}
};
class D : public C
{
OBJECT(D, C)
public:
D() {}
};
int main()
{
Object* o = new C();
A* a = object_cast<A>(o);
B* b = object_cast<B>(o);
C* c = object_cast<C>(o);
D* d = object_cast<D>(o);
std::cout << (a == nullptr ? "false" : "true") << std::endl;
std::cout << (b == nullptr ? "false" : "true") << std::endl;
std::cout << (c == nullptr ? "false" : "true") << std::endl;
std::cout << (d == nullptr ? "false" : "true") << std::endl;
return 0;
}
实现简易的C++ RTTI
最新推荐文章于 2024-08-16 08:17:29 发布