Gistrec

Template tree structure

Feb 21st, 2020 (edited)
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.70 KB | None | 0 0
  1. #ifndef TREE_NODE
  2. #define TREE_NODE
  3.  
  4. #include <string>
  5. #include <vector>
  6. #include <variant>
  7. #include <type_traits>
  8.  
  9.  
  10. namespace tree {
  11.  
  12. //! @brief Compares type for a set of types
  13. //!
  14. //! @tparam T    First object type
  15. //! @tparam Ts   Variadic types
  16. //!
  17. //! @return      True, if first type in the types; false otherwise
  18. //template <class T, class... Ts>
  19. //struct is_any : std::disjunction<std::is_same<T, Ts>...> {};
  20.  
  21. class Node {
  22. public:
  23.     using ChildrenType = std::vector<Node>;
  24.  
  25.     template <class T>
  26.     Node(const T value) : _value(value) {};
  27.  
  28.     template <class T, class Childs>
  29.     Node(const T value, const Childs& children) : _value(value), _children(children) {};
  30.  
  31.     template <class T>
  32.     auto get() {
  33.         return _value<T>
  34.     }
  35.  
  36.     template <class T>
  37.     void set(const T& value) {
  38.         _value = value;
  39.     }
  40.  
  41.     template <class T>
  42.     bool exists(const T& value) const {
  43.         for (const auto& child : _children) {
  44.             if (child.get() == value) return true;
  45.         }
  46.     }
  47.  
  48.     template <class T>
  49.     Node& operator[](const T& value) {
  50.         for (auto& child : _children) {
  51.             if (child.get() == value) return child;
  52.         }
  53.         throw "Child not found";
  54.     }
  55.  
  56.     size_t getStorageIndex() {
  57.         return _value.index();
  58.     }
  59.  
  60. private:
  61.     using StorageType  = std::variant<std::string, double, int>;
  62.  
  63.     template <class T>
  64.     struct StorageIndex { static_assert(false, "Storage type is string, double or int"); };
  65.  
  66.     template <> static struct StorageIndex<std::string> { size_t index = 0U; };
  67.     template <> static struct StorageIndex<double>      { size_t index = 1U; };
  68.     template <> static struct StorageIndex<int>         { size_t index = 2U; };
  69.  
  70.     StorageType  _value;
  71.     ChildrenType _children;
  72. };
  73.  
  74. } // namespace tree
  75.  
  76. #endif // !TREE_NODE
Add Comment
Please, Sign In to add comment