fork download
  1. #include <iostream>
  2. #include <memory>
  3. #include <utility>
  4. #include <vector>
  5.  
  6. template <typename T>
  7. class Tree : public std::enable_shared_from_this<Tree<T>>
  8. {
  9. public:
  10.  
  11. template<typename...Args>
  12. explicit Tree(Args&&...args) : m_data(std::forward<Args>(args)...) {}
  13.  
  14. std::shared_ptr<Tree> AddChild(const std::shared_ptr<Tree>& child)
  15. {
  16. using base = std::enable_shared_from_this<Tree>;
  17. m_children.push_back(child);
  18. child->m_parent = base::shared_from_this();
  19. return child;
  20. }
  21.  
  22. template<typename...Args>
  23. std::shared_ptr<Tree> CreateChild(Args&&...args)
  24. {
  25. return AddChild(std::make_shared<Tree>(std::forward<Args>(args)...));
  26. }
  27.  
  28. private:
  29. T m_data;
  30. std::weak_ptr<Tree> m_parent;
  31. std::vector<std::shared_ptr<Tree>> m_children;
  32. };
  33.  
  34. int main()
  35. {
  36. const auto root_ptr = std::make_shared<Tree<int>>();
  37. root_ptr->CreateChild(1)->CreateChild(11)->CreateChild(111);
  38. root_ptr->CreateChild(2)->CreateChild(21)->CreateChild(211);
  39. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Standard output is empty