Hasty Badger
Small UI library (a branch of Turbo Badger)
 All Classes Namespaces Functions Variables Enumerations Enumerator Friends Groups Pages
tb_object.h
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 
6 #ifndef TB_OBJECT_H
7 #define TB_OBJECT_H
8 
9 #include "tb_core.h"
10 #include "tb_linklist.h"
11 
12 namespace tb {
13 
14 typedef void* TB_TYPE_ID;
15 
16 /* TBTypedObject implements custom RTTI so we can get type safe casts,
17  and the class name at runtime.
18 
19  Each subclass is expected to define TBOBJECT_SUBCLASS to get the
20  necessary implementations, instead of implementing those manually. */
22 {
23 public:
24  virtual ~TBTypedObject() {}
25 
27  template<class T> static TB_TYPE_ID GetTypeId() { static char type_id; return &type_id; }
28 
30  virtual bool IsOfTypeId(const TB_TYPE_ID type_id) const { return type_id == GetTypeId<TBTypedObject>(); }
31 
33  template<class T> T *SafeCastTo() const { return (T*) (IsOfTypeId(GetTypeId<T>()) ? this : nullptr); }
34 
36  template<class T> bool IsOfType() const { return SafeCastTo<T>() ? true : false; }
37 
39  virtual const char *GetClassName() const { return "TBTypedObject"; }
40 };
41 
44 template<class T> T *TBSafeCast(TBTypedObject *obj) {
45  return obj ? obj->SafeCastTo<T>() : nullptr;
46 }
47 
50 template<class T> const T *TBSafeCast(const TBTypedObject *obj) {
51  return obj ? obj->SafeCastTo<T>() : nullptr;
52 }
53 
55 #define TBOBJECT_SUBCLASS(clazz, baseclazz) \
56  virtual const char *GetClassName() const { return #clazz; } \
57  virtual bool IsOfTypeId(const tb::TB_TYPE_ID type_id) const \
58  { return GetTypeId<clazz>() == type_id ? true : baseclazz::IsOfTypeId(type_id); }
59 
60 } // namespace tb
61 
62 #endif // TB_OBJECT_H
bool IsOfType() const
Return true if this object can safely be casted to the given type.
Definition: tb_object.h:36
Definition: tb_object.h:21
virtual bool IsOfTypeId(const TB_TYPE_ID type_id) const
Returns true if the class or the base class matches the type id.
Definition: tb_object.h:30
T * SafeCastTo() const
Returns this object as the given type or nullptr if it&#39;s not that type.
Definition: tb_object.h:33
T * TBSafeCast(TBTypedObject *obj)
Returns the given object as the given type, or nullptr if it&#39;s not that type or if the object is null...
Definition: tb_object.h:44
virtual const char * GetClassName() const
Get the classname of the object.
Definition: tb_object.h:39
static TB_TYPE_ID GetTypeId()
A static template method that returns a unique id for each type.
Definition: tb_object.h:27