openMSX
static_vector.hh
Go to the documentation of this file.
1 #ifndef STATIC_VECTOR_HH
2 #define STATIC_VECTOR_HH
3 
4 #include "span.hh"
5 #include <algorithm>
6 #include <cassert>
7 #include <cstddef>
8 #include <cstdint>
9 #include <initializer_list>
10 #include <limits>
11 #include <type_traits>
12 
13 // This is a _very_ minimal implementation of the following (we can easily
14 // extend this when the need arises).
15 //
16 // static_vector
17 // A dynamically-resizable vector with fixed capacity and embedded storage
18 // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0843r2.html
19 //
20 // For us the main purpose of this class is to use it during constexpr
21 // (compile-time) calculations. Because for now, it's no yet possible to use
22 // heap memory in constexpr functions (there are proposals to loosen this
23 // restriction in future C++ standards).
24 
25 template<typename T, size_t N>
27 {
28  using SizeType =
32  uint64_t>>>;
33 
34 public:
35  constexpr static_vector() = default;
36 
37  constexpr static_vector(std::initializer_list<T> list) {
38  assert(list.size() <= N);
39  std::copy(list.begin(), list.end(), data);
40  sz = SizeType(list.size());
41  }
42 
43  [[nodiscard]] constexpr const T* begin() const noexcept { return data; }
44  [[nodiscard]] constexpr const T* end() const noexcept { return data + sz; }
45 
46  [[nodiscard]] constexpr size_t size() const { return sz; }
47  [[nodiscard]] constexpr bool empty() const { return sz == 0; }
48 
49  [[nodiscard]] constexpr T& operator[](size_t index) { return data[index]; }
50  [[nodiscard]] constexpr const T& operator[](size_t index) const { return data[index]; }
51 
52  constexpr void push_back(const T& a) { assert(sz < N); data[sz++] = a; }
53 
54  constexpr void clear() { sz = 0; }
55 
56  operator span< T>() { return {data, sz}; }
57  operator span<const T>() const { return {data, sz}; }
58 
59 private:
60  T data[N] = {};
61  SizeType sz = 0;
62 };
63 
64 #endif
Definition: span.hh:126
constexpr void clear()
constexpr T & operator[](size_t index)
constexpr const T * begin() const noexcept
constexpr static_vector(std::initializer_list< T > list)
constexpr static_vector()=default
constexpr const T * end() const noexcept
constexpr size_t size() const
constexpr const T & operator[](size_t index) const
constexpr bool empty() const
constexpr void push_back(const T &a)
constexpr vecN< N, T > max(const vecN< N, T > &x, const vecN< N, T > &y)
Definition: gl_vec.hh:287
constexpr unsigned N
Definition: ResampleHQ.cc:228
auto copy(InputRange &&range, OutputIter out)
Definition: ranges.hh:179