tb_object.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // ================================================================================
  2. // == This file is a part of Turbo Badger. (C) 2011-2014, Emil Segerås ==
  3. // == See tb_core.h for more information. ==
  4. // ================================================================================
  5. #ifndef TB_OBJECT_H
  6. #define TB_OBJECT_H
  7. #include "tb_core.h"
  8. #include "tb_linklist.h"
  9. namespace tb {
  10. typedef void* TB_TYPE_ID;
  11. /* TBTypedObject implements custom RTTI so we can get type safe casts,
  12. and the class name at runtime.
  13. Each subclass is expected to define TBOBJECT_SUBCLASS to get the
  14. necessary implementations, instead of implementing those manually. */
  15. class TBTypedObject
  16. {
  17. public:
  18. virtual ~TBTypedObject() {}
  19. /** A static template method that returns a unique id for each type. */
  20. template<class T> static TB_TYPE_ID GetTypeId() { static char type_id; return &type_id; }
  21. /** Returns true if the class or the base class matches the type id */
  22. virtual bool IsOfTypeId(const TB_TYPE_ID type_id) const { return type_id == GetTypeId<TBTypedObject>(); }
  23. /** Returns this object as the given type or nullptr if it's not that type. */
  24. template<class T> T *SafeCastTo() const { return (T*) (IsOfTypeId(GetTypeId<T>()) ? this : nullptr); }
  25. /** Return true if this object can safely be casted to the given type. */
  26. template<class T> bool IsOfType() const { return SafeCastTo<T>() ? true : false; }
  27. /** Get the classname of the object. */
  28. virtual const char *GetClassName() const { return "TBTypedObject"; }
  29. };
  30. /** Returns the given object as the given type, or nullptr if it's not that type
  31. or if the object is nullptr. */
  32. template<class T> T *TBSafeCast(TBTypedObject *obj) {
  33. return obj ? obj->SafeCastTo<T>() : nullptr;
  34. }
  35. /** Returns the given object as the given type, or nullptr if it's not that type
  36. or if the object is nullptr. */
  37. template<class T> const T *TBSafeCast(const TBTypedObject *obj) {
  38. return obj ? obj->SafeCastTo<T>() : nullptr;
  39. }
  40. /** Implement the methods for safe typecasting without requiring RTTI. */
  41. #define TBOBJECT_SUBCLASS(clazz, baseclazz) \
  42. virtual const char *GetClassName() const { return #clazz; } \
  43. virtual bool IsOfTypeId(const TB_TYPE_ID type_id) const \
  44. { return GetTypeId<clazz>() == type_id ? true : baseclazz::IsOfTypeId(type_id); }
  45. }; // namespace tb
  46. #endif // TB_OBJECT_H