Object.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. #ifndef ANKI_UTIL_OBJECT_H
  2. #define ANKI_UTIL_OBJECT_H
  3. #include "anki/util/Assert.h"
  4. #include <vector>
  5. #include <boost/foreach.hpp>
  6. #include <boost/range/iterator_range.hpp>
  7. namespace anki {
  8. /// A hierarchical object
  9. template<typename T>
  10. class Object
  11. {
  12. public:
  13. typedef T Value;
  14. typedef std::vector<Value*> Container;
  15. typedef boost::iterator_range<typename Container::const_iterator>
  16. ConstIteratorRange;
  17. typedef boost::iterator_range<typename Container::iterator>
  18. MutableIteratorRange;
  19. /// Calls addChild if parent is not NULL
  20. /// @exception Exception
  21. Object(Value* self_, Value* parent_)
  22. : self(self_), parent(NULL)
  23. {
  24. ANKI_ASSERT(self != NULL && "Self can't be nullptr");
  25. if(parent_ != NULL)
  26. {
  27. parent_->addChild(self);
  28. }
  29. }
  30. /// Delete childs from the last entered to the first and update parent
  31. virtual ~Object()
  32. {
  33. if(parent != NULL)
  34. {
  35. parent->removeChild(self);
  36. }
  37. // Remove all children
  38. BOOST_FOREACH(Value* child, childs)
  39. {
  40. child->parent = NULL;
  41. }
  42. }
  43. /// @name Accessors
  44. /// @{
  45. const Value* getParent() const
  46. {
  47. return parent;
  48. }
  49. Value* getParent()
  50. {
  51. return parent;
  52. }
  53. ConstIteratorRange getChildren() const
  54. {
  55. return ConstIteratorRange(childs.begin(), childs.end());
  56. }
  57. MutableIteratorRange getChildren()
  58. {
  59. return MutableIteratorRange(childs.begin(), childs.end());
  60. }
  61. size_t getChildrenSize() const
  62. {
  63. return childs.size();
  64. }
  65. /// @}
  66. /// Add a new child
  67. void addChild(Value* child)
  68. {
  69. ANKI_ASSERT(child != NULL && "Null arg");
  70. ANKI_ASSERT(child->parent == NULL && "Child already has parent");
  71. child->parent = self;
  72. childs.push_back(child);
  73. }
  74. /// Remove a child
  75. void removeChild(Value* child)
  76. {
  77. ANKI_ASSERT(child != NULL && "Null arg");
  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 = NULL;
  83. }
  84. private:
  85. Value* self;
  86. Value* parent; ///< May be nullptr
  87. Container childs;
  88. };
  89. } // end namespace
  90. #endif