halcheck 1.0
Loading...
Searching...
No Matches
tree.hpp
1#ifndef HALCHECK_LIB_TREE_HPP
2#define HALCHECK_LIB_TREE_HPP
3
4#include <halcheck/lib/iterator.hpp>
5
6#include <unordered_map>
7#include <utility>
8
9namespace halcheck { namespace lib {
10
11template<typename K, typename V, template<typename...> class Map = std::unordered_map>
12class tree {
13private:
14 class box {
15 public:
16 box() : ptr(new tree()) {}
17 box(box &&other) noexcept(false) : ptr(new tree(std::move(*other))) {}
18 box(const box &other) : ptr(new tree(*other)) {}
19 box &operator=(box &&other) noexcept(false) {
20 if (this != other)
21 delete lib::exchange(ptr, new tree(std::move(*other)));
22 return *this;
23 }
24 box &operator=(const box &other) {
25 if (this != other)
26 delete lib::exchange(ptr, new tree(*other));
27 return *this;
28 }
29 ~box() { delete ptr; }
30
31 tree &operator*() { return *ptr; }
32 const tree &operator*() const { return *ptr; }
33 tree *operator->() { return ptr; }
34 const tree *operator->() const { return ptr; }
35
36 private:
37 tree *ptr;
38 };
39
40 struct unbox {
42 return {value.first, *value.second};
43 }
44 };
45
46 struct const_unbox {
47 std::pair<const K &, const tree &> operator()(const std::pair<const K, box> &value) const {
48 return {value.first, *value.second};
49 }
50 };
51
52 V _value;
53 Map<K, box> _children;
54
55public:
56 tree &operator[](const K &key) { return *_children[key]; }
57
58 tree &at(const K &key) { return *_children.at(key); }
59 const tree &at(const K &key) const { return *_children.at(key); }
60
61 V *get() {}
62 const V *get() const {}
63
64 V &operator*() { return *get(); }
65 const V &operator*() const { return *get(); }
66
67 V *operator->() { return get(); }
68 const V *operator->() const { return get(); }
69
70 using iterator = lib::transform_iterator<lib::iterator_t<Map<K, box>>, unbox>;
71 using const_iterator = lib::transform_iterator<lib::iterator_t<const Map<K, box>>, const_unbox>;
72
73 iterator begin() { return lib::make_transform_iterator(_children.begin(), unbox()); }
74 iterator end() { return lib::make_transform_iterator(_children.end(), unbox()); }
75
76 const_iterator begin() const { return lib::make_transform_iterator(_children.begin(), const_unbox()); }
77 const_iterator end() const { return lib::make_transform_iterator(_children.end(), const_unbox()); }
78
79 const_iterator cbegin() const { return lib::make_transform_iterator(_children.begin(), const_unbox()); }
80 const_iterator cend() const { return lib::make_transform_iterator(_children.end(), const_unbox()); }
81};
82
83}} // namespace halcheck::lib
84
85#endif
HALCHECK_INLINE_CONSTEXPR struct halcheck::lib::@30 make_transform_iterator
Constructs a transform_iterator.
T exchange(T &value, U &&next)
An implementation of std::exchange.
Definition utility.hpp:41
STL namespace.