doc_function_hooks.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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_function_hooks
  13. #include <boost/intrusive/list.hpp>
  14. #include <boost/intrusive/parent_from_member.hpp>
  15. using namespace boost::intrusive;
  16. struct MyClass
  17. {
  18. int dummy;
  19. //This internal type has a member hook
  20. struct InnerNode
  21. {
  22. int dummy;
  23. list_member_hook<> hook;
  24. } inner;
  25. };
  26. //This functor converts between MyClass and InnerNode's member hook
  27. struct Functor
  28. {
  29. //Required types
  30. typedef list_member_hook<> hook_type;
  31. typedef hook_type* hook_ptr;
  32. typedef const hook_type* const_hook_ptr;
  33. typedef MyClass value_type;
  34. typedef value_type* pointer;
  35. typedef const value_type* const_pointer;
  36. //Required static functions
  37. static hook_ptr to_hook_ptr (value_type &value)
  38. { return &value.inner.hook; }
  39. static const_hook_ptr to_hook_ptr(const value_type &value)
  40. { return &value.inner.hook; }
  41. static pointer to_value_ptr(hook_ptr n)
  42. {
  43. return get_parent_from_member<MyClass>
  44. (get_parent_from_member<MyClass::InnerNode>(n, &MyClass::InnerNode::hook)
  45. ,&MyClass::inner
  46. );
  47. }
  48. static const_pointer to_value_ptr(const_hook_ptr n)
  49. {
  50. return get_parent_from_member<MyClass>
  51. (get_parent_from_member<MyClass::InnerNode>(n, &MyClass::InnerNode::hook)
  52. ,&MyClass::inner
  53. );
  54. }
  55. };
  56. //Define a list that will use the hook accessed through the function object
  57. typedef list< MyClass, function_hook< Functor> > List;
  58. int main()
  59. {
  60. MyClass n;
  61. List l;
  62. //Insert the node in both lists
  63. l.insert(l.begin(), n);
  64. assert(l.size() == 1);
  65. return 0;
  66. }
  67. //]