tree.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // Copyright Oliver Kowalke 2014.
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See accompanying file LICENSE_1_0.txt or copy at
  4. // http://www.boost.org/LICENSE_1_0.txt)
  5. #ifndef TREE_H
  6. #define TREE_H
  7. #include <cstddef>
  8. #include <string>
  9. #include <boost/assert.hpp>
  10. #include <boost/config.hpp>
  11. #include <boost/intrusive_ptr.hpp>
  12. #if defined(_MSC_VER)
  13. # pragma warning(push)
  14. # pragma warning(disable:4355)
  15. #endif
  16. struct branch;
  17. struct leaf;
  18. struct visitor
  19. {
  20. virtual ~visitor() {};
  21. virtual void visit( branch & b) = 0;
  22. virtual void visit( leaf & l) = 0;
  23. };
  24. struct node
  25. {
  26. typedef boost::intrusive_ptr< node > ptr_t;
  27. std::size_t use_count;
  28. node() :
  29. use_count( 0)
  30. {}
  31. virtual ~node() {}
  32. virtual void accept( visitor & v) = 0;
  33. friend inline void intrusive_ptr_add_ref( node * p)
  34. { ++p->use_count; }
  35. friend inline void intrusive_ptr_release( node * p)
  36. { if ( 0 == --p->use_count) delete p; }
  37. };
  38. struct branch : public node
  39. {
  40. node::ptr_t left;
  41. node::ptr_t right;
  42. static ptr_t create( node::ptr_t left_, node::ptr_t right_)
  43. { return ptr_t( new branch( left_, right_) ); }
  44. branch( node::ptr_t left_, node::ptr_t right_) :
  45. left( left_), right( right_)
  46. {}
  47. void accept( visitor & v)
  48. { v.visit( * this); }
  49. };
  50. struct leaf : public node
  51. {
  52. std::string value;
  53. static ptr_t create( std::string const& value_)
  54. { return ptr_t( new leaf( value_) ); }
  55. leaf( std::string const& value_) :
  56. value( value_)
  57. {}
  58. void accept( visitor & v)
  59. { v.visit( * this); }
  60. };
  61. inline
  62. bool operator==( leaf const& l, leaf const& r)
  63. { return l.value == r.value; }
  64. inline
  65. bool operator!=( leaf const& l, leaf const& r)
  66. { return l.value != r.value; }
  67. #if defined(_MSC_VER)
  68. # pragma warning(pop)
  69. #endif
  70. #endif // TREE_H