forked from user1095108/generic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
implstore.hpp
119 lines (91 loc) · 2.38 KB
/
implstore.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#ifndef GNR_IMPLSTORE_HPP
# define GNR_IMPLSTORE_HPP
# pragma once
#include <cassert>
#include <cstddef>
#include <type_traits>
#include <utility>
namespace gnr
{
template <class U, std::size_t N = 64>
class implstore
{
typename std::aligned_storage_t<N> store_;
public:
static constexpr std::size_t const buffer_size = N;
using value_type = U;
template <typename ...A>
explicit implstore(A&& ...args)
{
static_assert(std::is_constructible<U, A...>{}, "cannot construct U");
static_assert(sizeof(store_) >= sizeof(U), "store_ too small");
::new (static_cast<void*>(&store_)) U(std::forward<A>(args)...);
}
~implstore() { get()->~U(); }
implstore(implstore const& other) : implstore(other, nullptr) { }
implstore(implstore&& other) : implstore(std::move(other), nullptr) { }
template <std::size_t M, typename K = U>
implstore(implstore<U, M> const& other,
std::enable_if_t<std::is_copy_constructible<K>{}>* = {})
{
::new (static_cast<void*>(&store_)) U(*other);
}
template <std::size_t M, typename K = U>
implstore(implstore<U, M>&& other,
std::enable_if_t<std::is_move_constructible<K>{}>* = nullptr)
{
::new (static_cast<void*>(&store_)) U(std::move(*other));
}
implstore& operator=(implstore const& rhs)
{
return operator=<N, U>(rhs);
}
template <std::size_t M, typename K = U,
typename = std::enable_if_t<std::is_copy_assignable<K>{}>
>
implstore& operator=(implstore<U, M> const& rhs)
{
assert(this != &rhs);
**this = *rhs;
return *this;
}
implstore& operator=(implstore&& rhs)
{
return operator=<N, U>(std::move(rhs));
}
template <std::size_t M, typename K = U,
typename = std::enable_if_t<std::is_move_assignable<K>{}>
>
implstore& operator=(implstore<U, M>&& rhs)
{
assert(this != &rhs);
**this = std::move(*rhs);
return *this;
}
auto operator->() noexcept
{
return reinterpret_cast<U*>(&store_);
}
auto operator->() const noexcept
{
return reinterpret_cast<U const*>(&store_);
}
auto& operator*() noexcept
{
return *reinterpret_cast<U*>(&store_);
}
auto& operator*() const noexcept
{
return *reinterpret_cast<U const*>(&store_);
}
auto get() noexcept
{
return reinterpret_cast<U*>(&store_);
}
auto get() const noexcept
{
return reinterpret_cast<U const*>(&store_);
}
};
}
#endif // GNR_IMPLSTORE_HPP