Skip to content

Commit 36c5423

Browse files
make variant ctor constexpr (#125)
* make variant ctor constexpr * make ~variant constexpr only for c++20 and up
1 parent 45798bd commit 36c5423

1 file changed

Lines changed: 14 additions & 6 deletions

File tree

include/cista/containers/variant.h

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -70,12 +70,12 @@ struct variant {
7070
using index_t = variant_index_t<T...>;
7171
static constexpr auto NO_VALUE = std::numeric_limits<index_t>::max();
7272

73-
variant() : idx_{NO_VALUE} {}
73+
constexpr variant() : idx_{NO_VALUE} {}
7474

7575
template <typename Arg,
7676
typename = std::enable_if_t<
7777
index_of_type<std::decay_t<Arg>, T...>() != TYPE_NOT_FOUND>>
78-
explicit variant(Arg&& arg)
78+
constexpr explicit variant(Arg&& arg)
7979
: idx_{static_cast<index_t>(index_of_type<Arg, T...>())} {
8080
#if defined(CISTA_ZERO_OUT)
8181
std::memset(&storage_, 0, sizeof(storage_));
@@ -123,8 +123,16 @@ struct variant {
123123
return *this;
124124
}
125125
}
126+
#if __cplusplus > 201703L
127+
constexpr
128+
#endif
129+
~variant() {
130+
destruct();
131+
}
132+
133+
bool valid() const { return index() != NO_VALUE; }
126134

127-
~variant() { destruct(); }
135+
operator bool() const { return valid(); }
128136

129137
friend bool operator==(variant const& a, variant const& b) noexcept {
130138
return a.idx_ == b.idx_
@@ -203,7 +211,7 @@ struct variant {
203211
}
204212
}
205213

206-
void destruct() {
214+
constexpr void destruct() {
207215
if (idx_ != NO_VALUE) {
208216
apply([](auto&& el) {
209217
using el_type = std::decay_t<decltype(el)>;
@@ -344,8 +352,8 @@ struct variant {
344352
});
345353
}
346354

347-
index_t idx_;
348-
std::aligned_union_t<0, T...> storage_;
355+
index_t idx_{NO_VALUE};
356+
std::aligned_union_t<0, T...> storage_{};
349357
};
350358

351359
template <typename T, typename... Ts>

0 commit comments

Comments
 (0)