Object.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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. if(parent_ != nullptr)
  23. {
  24. parent_->addChild(self);
  25. }
  26. parent = parent_;
  27. }
  28. /// Delete children from the last entered to the first and update parent
  29. virtual ~Object()
  30. {
  31. if(parent != nullptr)
  32. {
  33. parent->removeChild(self);
  34. }
  35. // Remove all children (fast version)
  36. for(Value* child : childs)
  37. {
  38. child->parent = nullptr;
  39. }
  40. }
  41. /// @name Accessors
  42. /// @{
  43. const Value* getParent() const
  44. {
  45. return parent;
  46. }
  47. Value* getParent()
  48. {
  49. return parent;
  50. }
  51. typename Container::const_iterator getChildrenBegin() const
  52. {
  53. return childs.begin();
  54. }
  55. typename Container::iterator getChildrenBegin()
  56. {
  57. return childs.begin();
  58. }
  59. typename Container::const_iterator getChildrenEnd() const
  60. {
  61. return childs.end();
  62. }
  63. typename Container::iterator getChildrenEnd()
  64. {
  65. return childs.end();
  66. }
  67. size_t getChildrenSize() const
  68. {
  69. return childs.size();
  70. }
  71. /// @}
  72. /// Add a new child
  73. void addChild(Value* child)
  74. {
  75. ANKI_ASSERT(child != nullptr && "Null arg");
  76. ANKI_ASSERT(child->parent == nullptr && "Child already has parent");
  77. child->parent = self;
  78. childs.push_back(child);
  79. }
  80. /// Remove a child
  81. void removeChild(Value* child)
  82. {
  83. ANKI_ASSERT(child != nullptr && "Null arg");
  84. ANKI_ASSERT(child->parent == self);
  85. typename Container::iterator it =
  86. std::find(childs.begin(), childs.end(), child);
  87. ANKI_ASSERT(it != childs.end() && "Child not found");
  88. childs.erase(it);
  89. child->parent = nullptr;
  90. }
  91. private:
  92. Value* self = nullptr;
  93. Value* parent = nullptr; ///< May be nullptr
  94. Container childs;
  95. };
  96. /// @}
  97. } // end namespace anki
  98. #endif