Object.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. #ifndef ANKI_UTIL_OBJECT_H
  2. #define ANKI_UTIL_OBJECT_H
  3. #include "anki/util/Assert.h"
  4. #include "anki/util/Vector.h"
  5. #include "anki/util/StdTypes.h"
  6. #include <algorithm>
  7. namespace anki {
  8. /// @addtogroup util
  9. /// @{
  10. /// A hierarchical object
  11. template<typename T>
  12. class Object
  13. {
  14. public:
  15. typedef T Value;
  16. typedef Vector<Value*> Container;
  17. /// Calls addChild if parent is not nullptr
  18. Object(Value* self_, Value* parent_)
  19. : self(self_)
  20. {
  21. ANKI_ASSERT(self != nullptr && "Self can't be nullptr");
  22. ANKI_ASSERT(parent_ != this && "Cannot put itself");
  23. if(parent_ != nullptr)
  24. {
  25. parent_->addChild(self);
  26. }
  27. parent = parent_;
  28. }
  29. /// Delete children from the last entered to the first and update parent
  30. virtual ~Object()
  31. {
  32. if(parent != nullptr)
  33. {
  34. parent->removeChild(self);
  35. }
  36. // Remove all children (fast version)
  37. for(Value* child : childs)
  38. {
  39. child->parent = nullptr;
  40. }
  41. }
  42. /// @name Accessors
  43. /// @{
  44. const Value* getParent() const
  45. {
  46. return parent;
  47. }
  48. Value* getParent()
  49. {
  50. return parent;
  51. }
  52. typename Container::const_iterator getChildrenBegin() const
  53. {
  54. return childs.begin();
  55. }
  56. typename Container::iterator getChildrenBegin()
  57. {
  58. return childs.begin();
  59. }
  60. typename Container::const_iterator getChildrenEnd() const
  61. {
  62. return childs.end();
  63. }
  64. typename Container::iterator getChildrenEnd()
  65. {
  66. return childs.end();
  67. }
  68. size_t getChildrenSize() const
  69. {
  70. return childs.size();
  71. }
  72. /// @}
  73. /// Add a new child
  74. void addChild(Value* child)
  75. {
  76. ANKI_ASSERT(child != nullptr && "Null arg");
  77. ANKI_ASSERT(child->parent == nullptr && "Child already has parent");
  78. child->parent = self;
  79. childs.push_back(child);
  80. }
  81. /// Remove a child
  82. void removeChild(Value* child)
  83. {
  84. ANKI_ASSERT(child != nullptr && "Null arg");
  85. ANKI_ASSERT(child->parent == self);
  86. typename Container::iterator it =
  87. std::find(childs.begin(), childs.end(), child);
  88. ANKI_ASSERT(it != childs.end() && "Child not found");
  89. childs.erase(it);
  90. child->parent = nullptr;
  91. }
  92. private:
  93. Value* self = nullptr;
  94. Value* parent = nullptr; ///< May be nullptr
  95. Container childs;
  96. };
  97. /// @}
  98. } // end namespace anki
  99. #endif