openMSX
static_vector.hh
Go to the documentation of this file.
1#ifndef STATIC_VECTOR_HH
2#define STATIC_VECTOR_HH
3
4#include <algorithm>
5#include <cassert>
6#include <cstddef>
7#include <cstdint>
8#include <initializer_list>
9#include <limits>
10#include <span>
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
25template<typename T, size_t N>
27{
28 using SizeType =
32 uint64_t>>>;
33
34public:
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 std::span< T>() { return {data, sz}; }
57 operator std::span<const T>() const { return {data, sz}; }
58
59private:
60 T data[N] = {};
61 SizeType sz = 0;
62};
63
64#endif
constexpr void clear()
constexpr const T * end() const noexcept
constexpr const T * begin() const noexcept
constexpr T & operator[](size_t index)
constexpr static_vector(std::initializer_list< T > list)
constexpr const T & operator[](size_t index) const
constexpr static_vector()=default
constexpr size_t size() 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:283
constexpr unsigned N
Definition: ResampleHQ.cc:226
auto copy(InputRange &&range, OutputIter out)
Definition: ranges.hh:208