From 36c542343af8aeb566f04e4db9b43317e6a8c49c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Felix=20G=C3=BCndling?= Date: Tue, 8 Feb 2022 18:51:35 +0100 Subject: [PATCH] make variant ctor constexpr (#125) * make variant ctor constexpr * make ~variant constexpr only for c++20 and up --- include/cista/containers/variant.h | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/include/cista/containers/variant.h b/include/cista/containers/variant.h index 91909b8c..50c1b6a1 100755 --- a/include/cista/containers/variant.h +++ b/include/cista/containers/variant.h @@ -70,12 +70,12 @@ struct variant { using index_t = variant_index_t; static constexpr auto NO_VALUE = std::numeric_limits::max(); - variant() : idx_{NO_VALUE} {} + constexpr variant() : idx_{NO_VALUE} {} template , T...>() != TYPE_NOT_FOUND>> - explicit variant(Arg&& arg) + constexpr explicit variant(Arg&& arg) : idx_{static_cast(index_of_type())} { #if defined(CISTA_ZERO_OUT) std::memset(&storage_, 0, sizeof(storage_)); @@ -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_ @@ -203,7 +211,7 @@ struct variant { } } - void destruct() { + constexpr void destruct() { if (idx_ != NO_VALUE) { apply([](auto&& el) { using el_type = std::decay_t; @@ -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