-
Notifications
You must be signed in to change notification settings - Fork 0
/
AnyTypeStorage.hpp
77 lines (61 loc) · 1.83 KB
/
AnyTypeStorage.hpp
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
#ifndef ANY_TYPE_STORAGE
#define ANY_TYPE_STORAGE
#include <vector>
#include <functional>
#include <cstdint>
namespace safini
{
class AnyTypeStorage
{
public:
template<typename T, typename... Args>
AnyTypeStorage(const std::in_place_type_t<T>, Args&&... args)
{
storageDestroyFunc = [](void* toDestroy)
{
//destructors can also throw sometimes...
try
{
std::destroy_at(std::launder(reinterpret_cast<T*>(toDestroy)));
}
catch(...){}
};
storage.resize(sizeof(T)+alignof(T)-1);
auto typeBeginInt = reinterpret_cast<std::uintptr_t>(storage.data())+alignof(T)-1;
typeBeginInt/=alignof(T);
typeBeginInt*=alignof(T);
std::construct_at(reinterpret_cast<T*>(typeBeginInt), std::forward<Args>(args)...);
typeBegin = reinterpret_cast<void*>(typeBeginInt);
}
AnyTypeStorage(const AnyTypeStorage&) = delete;
void operator=(const AnyTypeStorage&) = delete;
AnyTypeStorage(AnyTypeStorage&& anyTypeStorage):
storage(std::move(anyTypeStorage.storage)),
typeBegin(anyTypeStorage.typeBegin),
storageDestroyFunc(std::move(anyTypeStorage.storageDestroyFunc))
{
anyTypeStorage.typeBegin = nullptr;
}
void operator=(AnyTypeStorage&&) = delete;
template<typename T>
T& get() noexcept
{
return *std::launder(reinterpret_cast<T*>(typeBegin));
}
template<typename T>
const T& get() const noexcept
{
return *std::launder(reinterpret_cast<T*>(typeBegin));
}
~AnyTypeStorage()
{
if(typeBegin)
storageDestroyFunc(typeBegin);
}
private:
std::vector<uint8_t> storage{};
void* typeBegin = nullptr;
std::function<void(void*)> storageDestroyFunc{};
};
}
#endif // ANY_TYPE_STORAGE