GREM 3.12.0
Game/Rendering Engine Modules for C++
Loading...
Searching...
No Matches
Any.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Ivar Härnqvist
2// SPDX-License-Identifier: MIT
3
4#ifndef GREM_CORE_DATA_ANY_HPP
5#define GREM_CORE_DATA_ANY_HPP
6
8
10
11#include <cstddef> // std::size_t, std::byte
12#include <exception> // std::exception
13#include <memory> // std::construct_at, std::destroy_at
14#include <new> // std::launder
15#include <type_traits> // std::decay_t, std::is_..._v
16#include <utility> // std::move, std::forward, std::in_place_type...
17
18namespace grem {
19
25struct BadAnyAccess : std::exception {
26 BadAnyAccess() noexcept = default;
27
28 [[nodiscard]] const char* what() const noexcept override {
29 return "Bad any access.";
30 }
31};
32
40template <typename Base, std::size_t SmallCapacity = sizeof(void*) * 3, std::size_t SmallAlignment = alignof(void*)>
41class AnyBase {
42private:
43 struct FunctionTable {
44 void (*destroy)(AnyBase& self) noexcept;
45 void (*moveConstructOther)(AnyBase& self, AnyBase& other) noexcept;
46 void (*copyConstructOther)(const AnyBase& self, AnyBase& other);
47 void (*copyAssignOther)(const AnyBase& self, AnyBase& other);
48 Base* (*getValuePointer)(AnyBase& self) noexcept;
49 };
50
51 template <typename T>
52 static constexpr bool IS_SMALL = sizeof(T) <= SmallCapacity && alignof(T) <= SmallAlignment && std::is_nothrow_move_constructible_v<T>;
53
54 template <typename T>
55 static const FunctionTable* getFunctionTable() noexcept requires(IS_SMALL<T>) {
56 static_assert(std::is_void_v<Base> || std::is_base_of_v<Base, T>);
57 static constexpr FunctionTable FUNCTION_TABLE{
58 .destroy = [](AnyBase& self) noexcept -> void { std::destroy_at(reinterpret_cast<T*>(self.smallObject)); },
59 .moveConstructOther = [](AnyBase& self, AnyBase& other) noexcept -> void {
60 std::construct_at(reinterpret_cast<T*>(other.smallObject), std::move(*std::launder(reinterpret_cast<T*>(self.smallObject))));
61 other.functionTable = self.functionTable;
62 },
63 .copyConstructOther = [](const AnyBase& self, AnyBase& other) -> void {
64 std::construct_at(reinterpret_cast<T*>(other.smallObject), *std::launder(reinterpret_cast<const T*>(self.smallObject)));
65 other.functionTable = self.functionTable;
66 },
67 .copyAssignOther = [](const AnyBase& self, AnyBase& other) -> void {
68 if (other.functionTable == &FUNCTION_TABLE) {
69 *std::launder(reinterpret_cast<T*>(other.smallObject)) = *std::launder(reinterpret_cast<const T*>(self.smallObject));
70 } else {
71 if constexpr (std::is_nothrow_copy_constructible_v<T>) {
72 other.functionTable->destroy(other);
73 std::construct_at(reinterpret_cast<T*>(other.smallObject), *std::launder(reinterpret_cast<const T*>(self.smallObject)));
74 other.functionTable = self.functionTable;
75 } else {
76 T temporary = *std::launder(reinterpret_cast<const T*>(self.smallObject));
77 other.functionTable->destroy(other);
78 std::construct_at(reinterpret_cast<T*>(other.smallObject), std::move(temporary));
79 other.functionTable = self.functionTable;
80 }
81 }
82 },
83 .getValuePointer = [](AnyBase& self) noexcept -> Base* { return std::launder(reinterpret_cast<T*>(self.smallObject)); },
84 };
85 return &FUNCTION_TABLE;
86 }
87
88 template <typename T>
89 static const FunctionTable* getFunctionTable() noexcept requires(!IS_SMALL<T>) {
90 static_assert(std::is_void_v<Base> || std::is_base_of_v<Base, T>);
91 static constexpr FunctionTable FUNCTION_TABLE{
92 .destroy = [](AnyBase& self) noexcept -> void {
93 delete static_cast<T*>(self.largeObject); // NOLINT(cppcoreguidelines-owning-memory)
94 },
95 .moveConstructOther = [](AnyBase& self, AnyBase& other) noexcept -> void {
96 other.largeObject = self.largeObject;
97 other.functionTable = self.functionTable;
98 self.functionTable = &NULL_FUNCTION_TABLE;
99 },
100 .copyConstructOther = [](const AnyBase& self, AnyBase& other) -> void {
101 other.largeObject = new T{*static_cast<const T*>(self.largeObject)}; // NOLINT(cppcoreguidelines-owning-memory)
102 other.functionTable = self.functionTable;
103 },
104 .copyAssignOther = [](const AnyBase& self, AnyBase& other) -> void {
105 if (other.functionTable == &FUNCTION_TABLE) {
106 *static_cast<T*>(other.largeObject) = *static_cast<const T*>(self.largeObject);
107 } else {
108 T* const objectCopy = new T{*static_cast<const T*>(self.largeObject)}; // NOLINT(cppcoreguidelines-owning-memory)
109 other.functionTable->destroy(other);
110 other.largeObject = objectCopy;
111 other.functionTable = self.functionTable;
112 }
113 },
114 .getValuePointer = [](AnyBase& self) noexcept -> Base* { return self.largeObject; },
115 };
116 return &FUNCTION_TABLE;
117 }
118
119public:
135 template <typename T, typename... Args>
136 [[nodiscard]] static AnyBase create(Args&&... args) {
137 return AnyBase{InplaceTag{}, std::in_place_type<T>, std::forward<Args>(args)...};
138 }
139
143 constexpr AnyBase() noexcept
144 : functionTable(&NULL_FUNCTION_TABLE) {}
145
157 template <typename T>
158 AnyBase(T&& value) requires(!std::is_same_v<std::decay_t<T>, AnyBase>)
159 : AnyBase(InplaceTag{}, std::in_place_type<T>, std::forward<T>(value)) {}
160
163 functionTable->destroy(*this);
164 }
165
167 AnyBase(const AnyBase& other) {
168 other.functionTable->copyConstructOther(other, *this);
169 }
170
172 AnyBase(AnyBase&& other) noexcept {
173 other.functionTable->moveConstructOther(other, *this);
174 }
175
177 AnyBase& operator=(const AnyBase& other) {
178 if (this == &other) {
179 return *this;
180 }
181 other.functionTable->copyAssignOther(other, *this);
182 return *this;
183 }
184
186 AnyBase& operator=(AnyBase&& other) noexcept {
187 if (this == &other) {
188 return *this;
189 }
190 functionTable->destroy(*this);
191 other.functionTable->moveConstructOther(other, *this);
192 return *this;
193 }
194
198 void reset() noexcept {
199 functionTable->destroy(*this);
200 functionTable = &NULL_FUNCTION_TABLE;
201 }
202
219 template <typename T, typename... Args>
220 std::decay_t<T>& emplace(Args&&... args) {
221 reset();
222 using X = std::decay_t<T>;
223 X* result = nullptr;
224 if constexpr (IS_SMALL<X>) {
225 result = std::construct_at(reinterpret_cast<X*>(smallObject), std::forward<Args>(args)...);
226 } else {
227 result = new X(std::forward<Args>(args)...); // NOLINT(cppcoreguidelines-owning-memory)
228 largeObject = result;
229 }
230 functionTable = getFunctionTable<X>(); // NOLINT(cppcoreguidelines-prefer-member-initializer)
231 return *result;
232 }
233
242 [[nodiscard]] Base* base() noexcept {
243 return functionTable->getValuePointer(*this);
244 }
245
254 [[nodiscard]] const Base* base() const noexcept {
255 return functionTable->getValuePointer(*const_cast<AnyBase*>(this));
256 }
257
273 [[nodiscard]] Base* getUnsafeSmallObjectBasePointer() {
274#if defined(_WIN32) || defined(__linux__)
275 Base* const result = std::launder(reinterpret_cast<Base*>(smallObject));
276 GREM_ASSERT(result == base());
277 return result;
278#else
279 return base();
280#endif
281 }
282
298 [[nodiscard]] const Base* getUnsafeSmallObjectBasePointer() const {
299#if defined(_WIN32) || defined(__linux__)
300 const Base* const result = std::launder(reinterpret_cast<const Base*>(smallObject));
301 GREM_ASSERT(result == base());
302 return result;
303#else
304 return base();
305#endif
306 }
307
320 [[nodiscard]] Base* getUnsafeLargeObjectBasePointer() {
322 return largeObject;
323 }
324
337 [[nodiscard]] const Base* getUnsafeLargeObjectBasePointer() const {
339 return largeObject;
340 }
341
349 [[nodiscard]] auto& operator*() requires(!std::is_void_v<Base>) {
350 Base* const result = base();
351 GREM_ASSERT(result);
352 return *result;
353 }
354
363 [[nodiscard]] const auto& operator*() const requires(!std::is_void_v<Base>) {
364 const Base* const result = base();
365 GREM_ASSERT(result);
366 return *result;
367 }
368
376 [[nodiscard]] Base* operator->() requires(!std::is_void_v<Base>) {
377 Base* const result = base();
378 GREM_ASSERT(result);
379 return result;
380 }
381
389 [[nodiscard]] const Base* operator->() const requires(!std::is_void_v<Base>) {
390 const Base* const result = base();
391 GREM_ASSERT(result);
392 return result;
393 }
394
405 template <typename T>
406 [[nodiscard]] std::decay_t<T>* get_if() noexcept {
407 using X = std::decay_t<T>;
408 if (functionTable != getFunctionTable<X>()) {
409 return nullptr;
410 }
411 if constexpr (IS_SMALL<X>) {
412 return std::launder(reinterpret_cast<X*>(smallObject));
413 } else {
414 return largeObject;
415 }
416 }
417
429 template <typename T>
430 [[nodiscard]] const std::decay_t<T>* get_if() const noexcept {
431 using X = std::decay_t<T>;
432 if (functionTable != getFunctionTable<X>()) {
433 return nullptr;
434 }
435 if constexpr (IS_SMALL<X>) {
436 return std::launder(reinterpret_cast<const X*>(smallObject));
437 } else {
438 return largeObject;
439 }
440 }
441
454 template <typename T>
455 [[nodiscard]] std::decay_t<T>& get() {
456 std::decay_t<T>* const result = get_if<T>();
457 if (!result) {
458 throw BadAnyAccess{};
459 }
460 return *result;
461 }
462
475 template <typename T>
476 [[nodiscard]] const std::decay_t<T>& get() const {
477 const std::decay_t<T>* const result = get_if<T>();
478 if (!result) {
479 throw BadAnyAccess{};
480 }
481 return *result;
482 }
483
484private:
485 struct InplaceTag {};
486
487 template <typename T, typename... Args>
488 AnyBase(InplaceTag, std::in_place_type_t<T>, Args&&... args) {
489 using X = std::decay_t<T>;
490 if constexpr (IS_SMALL<X>) {
491 std::construct_at(reinterpret_cast<X*>(smallObject), std::forward<Args>(args)...);
492 } else {
493 largeObject = new X(std::forward<Args>(args)...); // NOLINT(cppcoreguidelines-owning-memory)
494 }
495 functionTable = getFunctionTable<X>(); // NOLINT(cppcoreguidelines-prefer-member-initializer)
496 }
497
498 static void nullDestroy(AnyBase&) noexcept {}
499 static void nullMoveConstructOther(AnyBase&, AnyBase& other) noexcept {
500 other.functionTable = &NULL_FUNCTION_TABLE;
501 }
502 static void nullCopyConstructOther(const AnyBase&, AnyBase& other) {
503 other.functionTable = &NULL_FUNCTION_TABLE;
504 }
505 static void nullCopyAssignOther(const AnyBase&, AnyBase& other) {
506 other.functionTable->destroy(other);
507 other.functionTable = &NULL_FUNCTION_TABLE;
508 }
509 static Base* nullGetValuePointer(AnyBase&) noexcept {
510 return nullptr;
511 }
512
513 static constexpr FunctionTable NULL_FUNCTION_TABLE{
514 .destroy = nullDestroy,
515 .moveConstructOther = nullMoveConstructOther,
516 .copyConstructOther = nullCopyConstructOther,
517 .copyAssignOther = nullCopyAssignOther,
518 .getValuePointer = nullGetValuePointer,
519 };
520
521 const FunctionTable* functionTable = &NULL_FUNCTION_TABLE;
522 union {
524 alignas(SmallAlignment) std::byte smallObject[SmallCapacity];
525 };
526};
527
532
533} // namespace grem
534
535#endif
#define GREM_ASSERT(expression)
Definition assertions.hpp:77
Generic type-erased semi-regular value wrapper.
Definition Any.hpp:41
Base * largeObject
Definition Any.hpp:523
const Base * getUnsafeLargeObjectBasePointer() const
Get a base pointer to the wrapped value, under the assumption that the value currently held by the wr...
Definition Any.hpp:337
const Base * operator->() const
Get a base pointer to the wrapped value.
Definition Any.hpp:389
const Base * getUnsafeSmallObjectBasePointer() const
Get a base pointer to the wrapped value, under the assumption that the value currently held by the wr...
Definition Any.hpp:298
AnyBase & operator=(AnyBase &&other) noexcept
Move assignment.
Definition Any.hpp:186
static AnyBase create(Args &&... args)
Create a wrapper of a new value.
Definition Any.hpp:136
Base * getUnsafeLargeObjectBasePointer()
Get a base pointer to the wrapped value, under the assumption that the value currently held by the wr...
Definition Any.hpp:320
Base * base() noexcept
Get a base pointer to the wrapped value.
Definition Any.hpp:242
std::decay_t< T > & get()
Access the wrapped value.
Definition Any.hpp:455
Base * operator->()
Get a base pointer to the wrapped value.
Definition Any.hpp:376
AnyBase & operator=(const AnyBase &other)
Copy assignment.
Definition Any.hpp:177
std::byte smallObject[SmallCapacity]
Definition Any.hpp:524
const std::decay_t< T > & get() const
Access the wrapped value.
Definition Any.hpp:476
const auto & operator*() const
Get a base reference to the wrapped value.
Definition Any.hpp:363
void reset() noexcept
Destroy the wrapped object if one exists, and reset the wrapper to empty.
Definition Any.hpp:198
constexpr AnyBase() noexcept
Construct an empty wrapper.
Definition Any.hpp:143
auto & operator*()
Get a base reference to the wrapped value.
Definition Any.hpp:349
AnyBase(T &&value)
Construct a wrapper from a value.
Definition Any.hpp:158
std::decay_t< T > & emplace(Args &&... args)
Destroy the wrapped object if one exists, then replace it with a new object.
Definition Any.hpp:220
const Base * base() const noexcept
Get a base pointer to the wrapped value.
Definition Any.hpp:254
~AnyBase()
Destructor.
Definition Any.hpp:162
const std::decay_t< T > * get_if() const noexcept
Try to get a pointer to the wrapped value.
Definition Any.hpp:430
AnyBase(const AnyBase &other)
Copy constructor.
Definition Any.hpp:167
Base * getUnsafeSmallObjectBasePointer()
Get a base pointer to the wrapped value, under the assumption that the value currently held by the wr...
Definition Any.hpp:273
std::decay_t< T > * get_if() noexcept
Try to get a pointer to the wrapped value.
Definition Any.hpp:406
AnyBase(AnyBase &&other) noexcept
Move constructor.
Definition Any.hpp:172
constexpr ComponentSwizzle< 0 > X
Tag specifying the X component at index 0 of a vector.
Definition quantities.hpp:1492
Definition aliases.hpp:9
AnyBase< void > Any
Type-erased semi-regular value wrapper.
Definition Any.hpp:531
Exception type that is thrown on an attempt to erroneously access the incorrect type of an Any wrappe...
Definition Any.hpp:25
BadAnyAccess() noexcept=default
const char * what() const noexcept override
Definition Any.hpp:28