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 16 using namespace boost::intrusive; 17 18 class Recursive; 19 20 //Declaration of the functor that converts betwen the Recursive 21 //class and the hook 22 struct Functor 23 { 24 //Required types 25 typedef list_member_hook<> hook_type; 26 typedef hook_type* hook_ptr; 27 typedef const hook_type* const_hook_ptr; 28 typedef Recursive value_type; 29 typedef value_type* pointer; 30 typedef const value_type* const_pointer; 31 32 //Required static functions 33 static hook_ptr to_hook_ptr (value_type &value); 34 static const_hook_ptr to_hook_ptr(const value_type &value); 35 static pointer to_value_ptr(hook_ptr n); 36 static const_pointer to_value_ptr(const_hook_ptr n); 37 }; 38 39 //Define the recursive class 40 class Recursive 41 { 42 private: 43 Recursive(const Recursive&); 44 Recursive & operator=(const Recursive&); 45 46 public: Recursive()47 Recursive() : hook(), children() {} 48 list_member_hook<> hook; 49 list< Recursive, function_hook< Functor> > children; 50 }; 51 52 //Definition of Functor functions to_hook_ptr(Functor::value_type & value)53inline Functor::hook_ptr Functor::to_hook_ptr (Functor::value_type &value) 54 { return &value.hook; } to_hook_ptr(const Functor::value_type & value)55inline Functor::const_hook_ptr Functor::to_hook_ptr(const Functor::value_type &value) 56 { return &value.hook; } to_value_ptr(Functor::hook_ptr n)57inline Functor::pointer Functor::to_value_ptr(Functor::hook_ptr n) 58 { return get_parent_from_member<Recursive>(n, &Recursive::hook); } to_value_ptr(Functor::const_hook_ptr n)59inline Functor::const_pointer Functor::to_value_ptr(Functor::const_hook_ptr n) 60 { return get_parent_from_member<Recursive>(n, &Recursive::hook); } 61 main()62int main() 63 { 64 Recursive f, f2; 65 //A recursive list of Recursive 66 list< Recursive, function_hook< Functor> > l; 67 68 //Insert a node in parent list 69 l.insert(l.begin(), f); 70 71 //Insert a node in child list 72 l.begin()->children.insert(l.begin()->children.begin(), f2); 73 74 //Objects properly inserted 75 assert(l.size() == l.begin()->children.size()); 76 assert(l.size() == 1); 77 78 //Clear both lists 79 l.begin()->children.clear(); 80 l.clear(); 81 return 0; 82 } 83 //] 84