Repository navigation
Expand file tree
/
Copy pathfallible.cpp
More file actions
82 lines (62 loc) · 1.74 KB
/
Copy pathfallible.cpp
File metadata and controls
82 lines (62 loc) · 1.74 KB
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
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include <beman/inplace_vector/inplace_vector.hpp>
#include <iostream>
using namespace beman::inplace_vector;
/*
* Helper function to print the contents of an inplace_vector.
*/
template <typename T, std::size_t Capacity>
void print_vector(const inplace_vector<T, Capacity> &vec,
const std::string_view name) {
std::cout << name << " [size=" << vec.size()
<< ", capacity=" << vec.capacity() << "]: ";
for (const auto &value : vec) {
std::cout << value << ' ';
}
std::cout << '\n';
}
/*
* Example struct to demonstrate inplace_vector with non-trivial types.
*/
struct Point {
int x;
int y;
};
std::ostream &operator<<(std::ostream &os, const Point &p) {
return os << '(' << p.x << ", " << p.y << ')';
}
int main() {
/*
* Checked API
*
* try_* operations fail gracefully instead of overflowing capacity.
*/
std::cout << "----- Checked API -----\n";
inplace_vector<int, 2> checked;
if (checked.try_push_back(10)) {
std::cout << "Inserted 10\n";
}
if (checked.try_push_back(20)) {
std::cout << "Inserted 20\n";
}
if (!checked.try_push_back(30)) {
std::cout << "Failed to insert 30: vector is full\n";
}
print_vector(checked, "checked");
/*
* Unchecked API
*
* unchecked_* operations skip capacity checks and require that
* the caller guarantees enough remaining space.
*/
std::cout << "\n----- Unchecked API -----\n";
inplace_vector<Point, 2> unchecked;
unchecked.unchecked_emplace_back(1, 2);
unchecked.unchecked_emplace_back(3, 4);
print_vector(unchecked, "unchecked");
/*
* unchecked.unchecked_emplace_back(5, 6);
* Undefined behavior: capacity exceeded.
*/
return 0;
}