cepxuozab

ExampleBuilderStack

Jan 22nd, 2025
327
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. #include <cassert>
  2. #include <iostream>
  3. #include <string>
  4. #include <variant>
  5. #include <vector>
  6.  
  7. using namespace std::literals;
  8.  
  9. class Node {
  10.     using Value = std::variant<nullptr_t, std::string, std::vector<Node>>;
  11.     Value value_;
  12.  
  13. public:
  14.     Node() = default;
  15.     template <typename T>
  16.     Node(T value)
  17.         : value_(std::move(value))
  18.     {
  19.     }
  20.     Value& GetValue() { return value_; }
  21. };
  22.  
  23. int main()
  24. {
  25.     Node root;
  26.     std::vector<Node*> stack_ { &root };
  27.     // StartArray
  28.     auto& curr_value = stack_.back()->GetValue();
  29.     assert(std::holds_alternative<nullptr_t>(curr_value));
  30.     curr_value = std::move(std::vector<Node> {});
  31.     // Add value to array on stack
  32.     auto& new_node = stack_.back()->GetValue();
  33.     assert(std::holds_alternative<std::vector<Node>>(new_node));
  34.     auto& node = std::get<std::vector<Node>>(new_node).emplace_back("simple_string");
  35.     // the top of the stack is still an array
  36.     auto new_back = stack_.back()->GetValue();
  37.     assert(std::holds_alternative<std::vector<Node>>(new_back));
  38.     // end array
  39.     stack_.pop_back();
  40.     auto& value = root.GetValue();
  41.     assert(std::holds_alternative<std::vector<Node>>(value));
  42.     std::cout << std::get<std::vector<Node>>(value).size() << '\n';
  43.     auto simple_string = std::get<std::vector<Node>>(value).front();
  44.     std::cout << std::get<std::string>(simple_string.GetValue());
  45. }
  46.  
Advertisement
Add Comment
Please, Sign In to add comment