Skip to content

Commit

Permalink
make variant ctor constexpr (#125)
Browse files Browse the repository at this point in the history
* make variant ctor constexpr

* make ~variant constexpr only for c++20 and up
  • Loading branch information
felixguendling authored Feb 8, 2022
1 parent 45798bd commit 36c5423
Showing 1 changed file with 14 additions and 6 deletions.
20 changes: 14 additions & 6 deletions include/cista/containers/variant.h
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,12 @@ struct variant {
using index_t = variant_index_t<T...>;
static constexpr auto NO_VALUE = std::numeric_limits<index_t>::max();

variant() : idx_{NO_VALUE} {}
constexpr variant() : idx_{NO_VALUE} {}

template <typename Arg,
typename = std::enable_if_t<
index_of_type<std::decay_t<Arg>, T...>() != TYPE_NOT_FOUND>>
explicit variant(Arg&& arg)
constexpr explicit variant(Arg&& arg)
: idx_{static_cast<index_t>(index_of_type<Arg, T...>())} {
#if defined(CISTA_ZERO_OUT)
std::memset(&storage_, 0, sizeof(storage_));
Expand Down Expand Up @@ -123,8 +123,16 @@ struct variant {
return *this;
}
}
#if __cplusplus > 201703L
constexpr
#endif
~variant() {
destruct();
}

bool valid() const { return index() != NO_VALUE; }

~variant() { destruct(); }
operator bool() const { return valid(); }

friend bool operator==(variant const& a, variant const& b) noexcept {
return a.idx_ == b.idx_
Expand Down Expand Up @@ -203,7 +211,7 @@ struct variant {
}
}

void destruct() {
constexpr void destruct() {
if (idx_ != NO_VALUE) {
apply([](auto&& el) {
using el_type = std::decay_t<decltype(el)>;
Expand Down Expand Up @@ -344,8 +352,8 @@ struct variant {
});
}

index_t idx_;
std::aligned_union_t<0, T...> storage_;
index_t idx_{NO_VALUE};
std::aligned_union_t<0, T...> storage_{};
};

template <typename T, typename... Ts>
Expand Down

0 comments on commit 36c5423

Please sign in to comment.