doc_recursive_member.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /////////////////////////////////////////////////////////////////////////////
  2. //
  3. // (C) Copyright Ion Gaztanaga 2010-2013
  4. //
  5. // Distributed under the Boost Software License, Version 1.0.
  6. // (See accompanying file LICENSE_1_0.txt or copy at
  7. // http://www.boost.org/LICENSE_1_0.txt)
  8. //
  9. // See http://www.boost.org/libs/intrusive for documentation.
  10. //
  11. /////////////////////////////////////////////////////////////////////////////
  12. //[doc_recursive_member
  13. #include <boost/intrusive/list.hpp>
  14. #include <boost/intrusive/parent_from_member.hpp>
  15. using namespace boost::intrusive;
  16. class Recursive;
  17. //Declaration of the functor that converts betwen the Recursive
  18. //class and the hook
  19. struct Functor
  20. {
  21. //Required types
  22. typedef list_member_hook<> hook_type;
  23. typedef hook_type* hook_ptr;
  24. typedef const hook_type* const_hook_ptr;
  25. typedef Recursive value_type;
  26. typedef value_type* pointer;
  27. typedef const value_type* const_pointer;
  28. //Required static functions
  29. static hook_ptr to_hook_ptr (value_type &value);
  30. static const_hook_ptr to_hook_ptr(const value_type &value);
  31. static pointer to_value_ptr(hook_ptr n);
  32. static const_pointer to_value_ptr(const_hook_ptr n);
  33. };
  34. //Define the recursive class
  35. class Recursive
  36. {
  37. private:
  38. Recursive(const Recursive&);
  39. Recursive & operator=(const Recursive&);
  40. public:
  41. Recursive() : hook(), children() {}
  42. list_member_hook<> hook;
  43. list< Recursive, function_hook< Functor> > children;
  44. };
  45. //Definition of Functor functions
  46. inline Functor::hook_ptr Functor::to_hook_ptr (Functor::value_type &value)
  47. { return &value.hook; }
  48. inline Functor::const_hook_ptr Functor::to_hook_ptr(const Functor::value_type &value)
  49. { return &value.hook; }
  50. inline Functor::pointer Functor::to_value_ptr(Functor::hook_ptr n)
  51. { return get_parent_from_member<Recursive>(n, &Recursive::hook); }
  52. inline Functor::const_pointer Functor::to_value_ptr(Functor::const_hook_ptr n)
  53. { return get_parent_from_member<Recursive>(n, &Recursive::hook); }
  54. int main()
  55. {
  56. Recursive f, f2;
  57. //A recursive list of Recursive
  58. list< Recursive, function_hook< Functor> > l;
  59. //Insert a node in parent list
  60. l.insert(l.begin(), f);
  61. //Insert a node in child list
  62. l.begin()->children.insert(l.begin()->children.begin(), f2);
  63. //Objects properly inserted
  64. assert(l.size() == l.begin()->children.size());
  65. assert(l.size() == 1);
  66. //Clear both lists
  67. l.begin()->children.clear();
  68. l.clear();
  69. return 0;
  70. }
  71. //]