plcopen 0.22.0
载入中...
搜索中...
未找到
static_vector.h
浏览该文件的文档.
1#pragma once
2
3#include <array>
4#include <cstddef>
5#include <type_traits>
6
7#include "rt/error.h"
8
9namespace plcopen::core::rt
10{
11
12template <typename T, std::size_t Capacity> class StaticVector
13{
14public:
15 static_assert(Capacity > 0, "StaticVector capacity must be positive");
16 // Storage is an eagerly-constructed std::array; pop_back()/clear() only
17 // adjust the size and never destroy elements, and push_back assigns into
18 // pre-constructed slots. That contract is only sound for trivial element
19 // types — fence it so a non-trivial type cannot silently "revive"
20 // dropped elements. (is_default_constructible is deliberately NOT
21 // asserted: nested aggregates with NSDMIs instantiated from inside their
22 // enclosing class would fail it spuriously.)
23 static_assert(std::is_trivially_destructible_v<T>,
24 "StaticVector stores elements eagerly and pop_back()/clear() only adjust "
25 "size; T must be trivially destructible");
26 static_assert(std::is_trivially_copyable_v<T>,
27 "StaticVector assigns into pre-constructed storage; T must be trivially "
28 "copyable");
29
30 constexpr std::size_t size() const
31 {
32 return size_;
33 }
34
35 constexpr std::size_t capacity() const
36 {
37 return Capacity;
38 }
39
40 constexpr bool empty() const
41 {
42 return size_ == 0;
43 }
44
45 constexpr bool full() const
46 {
47 return size_ == Capacity;
48 }
49
50 constexpr ErrorCode push_back(const T &value)
51 {
52 if(full()) {
54 }
55 data_[size_] = value;
56 ++size_;
57 return ErrorCode::ok;
58 }
59
60 constexpr ErrorCode pop_back()
61 {
62 if(empty()) {
64 }
65 --size_;
66 return ErrorCode::ok;
67 }
68
69 constexpr void clear()
70 {
71 size_ = 0;
72 }
73
74 constexpr T &operator[](std::size_t index)
75 {
76 return data_[index];
77 }
78
79 constexpr const T &operator[](std::size_t index) const
80 {
81 return data_[index];
82 }
83
84 constexpr const T *data() const
85 {
86 return data_.data();
87 }
88
89 constexpr T *data()
90 {
91 return data_.data();
92 }
93
94private:
95 std::array<T, Capacity> data_{};
96 std::size_t size_ = 0;
97};
98
99} // namespace plcopen::core::rt
constexpr std::size_t size() const
constexpr ErrorCode push_back(const T &value)
constexpr std::size_t capacity() const
constexpr const T & operator[](std::size_t index) const
constexpr T & operator[](std::size_t index)
constexpr const T * data() const