Gistrec icon

Template tree structure

Gistrec | PRO | 10/05/20 07:33:28 AM UTC (Edited) | 0 ⭐ | 595 👁️ | Never ⏰ | []
C++ |

1.7 KB

|

None

|

0 👍

/

0 👎

#ifndef TREE_NODE
#define TREE_NODE
 
#include <string>
#include <vector>
#include <variant>
#include <type_traits>
 
 
namespace tree {
 
//! @brief Compares type for a set of types
//!
//! @tparam T    First object type
//! @tparam Ts   Variadic types
//!
//! @return      True, if first type in the types; false otherwise
//template <class T, class... Ts>
//struct is_any : std::disjunction<std::is_same<T, Ts>...> {};
 
class Node {
public:
    using ChildrenType = std::vector<Node>;
 
    template <class T>
    Node(const T value) : _value(value) {};
 
    template <class T, class Childs>
    Node(const T value, const Childs& children) : _value(value), _children(children) {};
 
    template <class T>
    auto get() {
        return _value<T>
    }
 
    template <class T>
    void set(const T& value) {
        _value = value;
    }
 
    template <class T>
    bool exists(const T& value) const {
        for (const auto& child : _children) {
            if (child.get() == value) return true;
        }
    }
 
    template <class T>
    Node& operator[](const T& value) {
        for (auto& child : _children) {
            if (child.get() == value) return child;
        }
        throw "Child not found";
    }
 
    size_t getStorageIndex() {
        return _value.index();
    }
 
private:
    using StorageType  = std::variant<std::string, double, int>;
 
    template <class T>
    struct StorageIndex { static_assert(false, "Storage type is string, double or int"); };
 
    template <> static struct StorageIndex<std::string> { size_t index = 0U; };
    template <> static struct StorageIndex<double>      { size_t index = 1U; };
    template <> static struct StorageIndex<int>         { size_t index = 2U; };
 
    StorageType  _value;
    ChildrenType _children;
};
 
} // namespace tree
 
#endif // !TREE_NODE

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎