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