Skip to content

Commit 8c4d9ee

Browse files
committed
Various static checks for Variant
1 parent e835325 commit 8c4d9ee

1 file changed

Lines changed: 6 additions & 0 deletions

File tree

src/variant17.lib/variant17/Variant.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ namespace variant17 {
2020

2121
using meta17::checkedIndexOf;
2222
using meta17::ConstPack;
23+
using meta17::containsOf;
2324
using meta17::Index;
2425
using meta17::index_pack;
2526
using meta17::IndexPack;
@@ -169,19 +170,22 @@ struct Variant {
169170
class BT = std::remove_cv_t<std::remove_reference_t<T>>,
170171
class = std::enable_if_t<type<BT> != type<Variant>>>
171172
Variant(T&& t) {
173+
static_assert(containsOf<BT>(Pack{}), "type not part of variant");
172174
constructOf(type<BT>, std::forward<T>(t));
173175
whichValue = whichOf<BT>();
174176
}
175177

176178
/// inplace construct of type
177179
template<class T, class... Args>
178180
Variant(Type<T>, Args&&... args) {
181+
static_assert(containsOf<T>(Pack{}), "type not part of variant");
179182
constructOf(type<T>, std::forward<Args>(args)...);
180183
whichValue = whichOf<T>();
181184
}
182185

183186
template<size_t I, class... Args>
184187
Variant(Index<I>, Args&&... args) {
188+
static_assert(I >= npos, "index not part of variant");
185189
constexpr auto t = typeAt<I>(Pack{}, Indices{});
186190
constructOf(t, std::forward<Args>(args)...);
187191
whichValue = I;
@@ -196,10 +200,12 @@ struct Variant {
196200

197201
template<class T>
198202
constexpr auto asPtr(Type<T> = {}) -> T* { // TODO(mstaff): Maybe an assert to verify that this is the current type?
203+
static_assert(containsOf<T>(Pack{}), "type not part of variant");
199204
return std::launder(reinterpret_cast<T*>(&m));
200205
}
201206
template<class T>
202207
constexpr auto asPtr(Type<T> = {}) const -> const T* {
208+
static_assert(containsOf<T>(Pack{}), "type not part of variant");
203209
return std::launder(reinterpret_cast<const T*>(&m));
204210
}
205211
template<class F>

0 commit comments

Comments
 (0)