-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_flex_array.cpp
83 lines (64 loc) · 1.91 KB
/
example_flex_array.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <dice/template-library/flex_array.hpp>
#include <cstddef>
#include <iostream>
#include <variant>
using namespace dice::template_library;
// multidimensional-shape polymorphism without heap allocation
static constexpr size_t shape_max_dim = 2;
using shape_extents = flex_array<size_t, dynamic_extent, shape_max_dim>;
struct point {
flex_array<size_t, 0> extent;
[[nodiscard]] shape_extents get_extents() const noexcept {
return extent;
}
};
struct line {
flex_array<size_t, 1> length;
[[nodiscard]] shape_extents get_extents() const noexcept {
return length;
}
};
struct square {
flex_array<size_t, 2> width_height;
[[nodiscard]] shape_extents get_extents() const noexcept {
return width_height;
}
};
#if __has_include(<ankerl/svector.h>)
struct arbitrary_high_dimensional_thing {
flex_array<size_t, 2, dynamic_extent> extents;
};
#endif // __has_include
struct shape {
std::variant<point, line, square> shape_;
[[nodiscard]] shape_extents get_extents() const noexcept {
return std::visit([](auto const &sha) {
return sha.get_extents();
}, shape_);
}
};
// minimal size of static-length flex_arrays
static_assert(sizeof(point) == 1);
static_assert(sizeof(line) == sizeof(size_t));
static_assert(sizeof(square) == sizeof(size_t) * 2);
// no heap allocations on shape_extents
static_assert(sizeof(shape_extents) == sizeof(size_t) * 2 + sizeof(size_t));
void print_extents(shape const &sha) {
for (auto const ext : sha.get_extents()) {
std::cout << ext << " ";
}
}
int main() {
shape const point1{point{.extent = {}}};
shape const line1{line{.length = {12}}};
shape const square1{square{.width_height = {52, 15}}};
print_extents(point1);
print_extents(line1);
print_extents(square1);
#if __has_include(<ankerl/svector.h>)
arbitrary_high_dimensional_thing thing{.extents = {1, 2, 3, 4, 5, 6, 7, 8}};
for (auto const ext : thing.extents) {
std::cout << ext << " ";
}
#endif // __has_include
}