codac 1.5.6
Loading...
Searching...
No Matches
codac2_Collection.h
Go to the documentation of this file.
1
9
10#pragma once
11
12#include <type_traits>
13#include <cassert>
14#include <vector>
15#include <memory>
16
17namespace codac2
18{
19 template<typename T>
20 class Collection
21 {
22 public:
23
24 Collection()
25 { }
26
27 template<typename... T_>
28 requires ((std::is_base_of_v<T,T_> // T_ should be some T class
29 && !std::is_same_v<Collection<T>,T_>) && ...)
30 Collection(const T_&... x)
31 {
32 (add_shared_ptr(std::make_shared<T_>(x)), ...);
33 }
34
35 template<typename... T_>
36 requires (std::is_same_v<std::shared_ptr<T>,std::shared_ptr<T_>> && ...)
37 Collection(const std::shared_ptr<T_>&... x)
38 {
39 (add_shared_ptr(x), ...);
40 }
41
42 Collection(const Collection<T>& c)
43 {
44 for(const auto& ci : c._v)
45 add_shared_ptr(std::dynamic_pointer_cast<T>(ci->copy()));
46 }
47
48 template<typename T_>
49 requires std::is_base_of_v<T,T_>
50 void add(const T_& x)
51 {
52 add_shared_ptr(std::make_shared<T>(x));
53 }
54
55 void add_shared_ptr(std::shared_ptr<T> shrd_ptr)
56 {
57 assert(shrd_ptr);
58 _v.push_back(shrd_ptr);
59 _v_raw.push_back(shrd_ptr.get());
60 }
61
62 void add_raw_ptr(T *x)
63 {
64 assert(x);
65 _v_raw.push_back(x);
66 }
67
68 using iterator = typename std::vector<T*>::iterator;
69 using const_iterator = typename std::vector<T*>::const_iterator;
70
71 T& front()
72 {
73 return const_cast<T&>(const_cast<const Collection<T>*>(this)->front());
74 }
75
76 const T& front() const
77 {
78 assert(!_v_raw.empty());
79 return *_v_raw.front();
80 }
81
82 T& back()
83 {
84 return const_cast<T&>(const_cast<const Collection<T>*>(this)->back());
85 }
86
87 const T& back() const
88 {
89 assert(!_v_raw.empty());
90 return *_v_raw.back();
91 }
92
93 iterator begin()
94 {
95 return const_cast<iterator>(const_cast<const Collection<T>*>(this)->begin());
96 }
97
98 const_iterator begin() const
99 {
100 return _v_raw.cbegin();
101 }
102
103 const_iterator end() const
104 {
105 return _v_raw.cend();
106 }
107
108 iterator end()
109 {
110 return const_cast<iterator>(const_cast<const Collection<T>*>(this)->end());
111 }
112
113 private:
114
115 std::vector<std::shared_ptr<T>> _v;
116 std::vector<T*> _v_raw;
117 };
118}