Object.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #ifndef ANKI_UTIL_OBJECT_H
  2. #define ANKI_UTIL_OBJECT_H
  3. #include "anki/util/Assert.h"
  4. #include <vector>
  5. #include <boost/range/iterator_range.hpp>
  6. namespace anki {
  7. /// A hierarchical object
  8. template<typename T>
  9. class Object
  10. {
  11. public:
  12. typedef T Value;
  13. typedef std::vector<Value*> Container;
  14. typedef boost::iterator_range<typename Container::const_iterator>
  15. ConstIteratorRange;
  16. typedef boost::iterator_range<typename Container::iterator>
  17. MutableIteratorRange;
  18. /// Calls addChild if parent is not nullptr
  19. Object(Value* self_, Value* parent_)
  20. : self(self_)
  21. {
  22. ANKI_ASSERT(self != nullptr && "Self can't be nullptr");
  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. ConstIteratorRange getChildren() const
  53. {
  54. return ConstIteratorRange(childs.begin(), childs.end());
  55. }
  56. MutableIteratorRange getChildren()
  57. {
  58. return MutableIteratorRange(childs.begin(), childs.end());
  59. }
  60. size_t getChildrenSize() const
  61. {
  62. return childs.size();
  63. }
  64. /// @}
  65. /// Add a new child
  66. void addChild(Value* child)
  67. {
  68. ANKI_ASSERT(child != nullptr && "Null arg");
  69. ANKI_ASSERT(child->parent == nullptr && "Child already has parent");
  70. child->parent = self;
  71. childs.push_back(child);
  72. }
  73. /// Remove a child
  74. void removeChild(Value* child)
  75. {
  76. ANKI_ASSERT(child != nullptr && "Null arg");
  77. ANKI_ASSERT(child->parent == self);
  78. typename Container::iterator it =
  79. std::find(childs.begin(), childs.end(), child);
  80. ANKI_ASSERT(it != childs.end() && "Child not found");
  81. childs.erase(it);
  82. child->parent = nullptr;
  83. }
  84. private:
  85. Value* self = nullptr;
  86. Value* parent = nullptr; ///< May be nullptr
  87. Container childs;
  88. };
  89. } // end namespace
  90. #endif