fork download
  1. /*
  2. I'm playing around with Boost Variant in order to create a tree made out of nodes
  3. that can either be a value (leaf), or a set of one or two children
  4.  
  5. The problem is that nesting doesn't work for a single child case - I have wrong depth here
  6.  
  7. */
  8.  
  9. #define BOOST_VARIANT_NO_FULL_RECURSIVE_VARIANT_SUPPORT
  10. #include <boost/variant.hpp>
  11.  
  12. #include <iostream>
  13. #include <typeinfo>
  14.  
  15. typedef boost::make_recursive_variant<
  16. // can be one of
  17. int,
  18. bool,
  19. boost::recursive_variant_, // single child
  20. std::pair<boost::recursive_variant_, boost::recursive_variant_> // two children
  21. >::type Node;
  22.  
  23. struct TreePrint : public boost::static_visitor<void> {
  24. mutable int depth;
  25. template <typename T>
  26. void operator()(const T& value) const {
  27. depth++;
  28. std::cout << "[depth " << depth << "]: " << value << std::endl;
  29. depth--;
  30. }
  31.  
  32. void operator()(const Node& value) const {
  33. depth++;
  34. boost::apply_visitor(*this, value);
  35. depth--;
  36. }
  37.  
  38. void operator()(const std::pair<Node, Node>& value) const {
  39. depth++;
  40. boost::apply_visitor(*this, value.first);
  41. boost::apply_visitor(*this, value.second);
  42. depth--;
  43. }
  44. };
  45.  
  46. int main() {
  47. /*
  48.   root
  49.   / \
  50.   i1 i2
  51.   / \ \
  52.   t1 5 t1
  53.   / \ \
  54.   1 true 10
  55.  
  56.   */
  57.  
  58. Node root(
  59. std::pair<Node, Node>(
  60. std::pair<Node, Node>( // i1
  61. std::pair<Node, Node>( // t1
  62. 1,
  63. true
  64. ),
  65. 5
  66. ),
  67. Node( // i2
  68. Node( // t1
  69. Node(10) // ERROR - should have depth 4
  70. )
  71. )
  72. )
  73. );
  74.  
  75. boost::apply_visitor(TreePrint(), root );
  76. }
Success #stdin #stdout 0s 3436KB
stdin
Standard input is empty
stdout
[depth 4]: 1
[depth 4]: 1
[depth 3]: 5
[depth 2]: 10