From e1ba7dd7a976b2ce076b9361f761dd51cdf4b4ec Mon Sep 17 00:00:00 2001 From: Steven Le Rouzic Date: Thu, 8 May 2025 00:15:26 +0200 Subject: Add enum underlying utilities --- asl/base/meta.hpp | 2 ++ asl/base/meta_tests.cpp | 7 +++++++ asl/base/utility.hpp | 6 ++++++ asl/base/utility_tests.cpp | 17 +++++++++++++++++ 4 files changed, 32 insertions(+) (limited to 'asl') diff --git a/asl/base/meta.hpp b/asl/base/meta.hpp index c13439a..3675df3 100644 --- a/asl/base/meta.hpp +++ b/asl/base/meta.hpp @@ -309,6 +309,8 @@ template using as_signed_integer = _integer_traits:: template concept is_enum = __is_enum(T); +template using underlying_t = __underlying_type(T); + template struct is_uniquely_represented : false_type {}; template struct is_uniquely_represented : true_type {}; template struct is_uniquely_represented : true_type {}; diff --git a/asl/base/meta_tests.cpp b/asl/base/meta_tests.cpp index c221dcf..7bae295 100644 --- a/asl/base/meta_tests.cpp +++ b/asl/base/meta_tests.cpp @@ -372,3 +372,10 @@ static_assert(!asl::same_as, int*>); static_assert(!asl::same_as, int**>); static_assert(asl::same_as, int(*)[2]>); static_assert(asl::same_as, int(*)(int)>); + +enum EnumU8 : uint8_t {}; +enum EnumI64 : int64_t {}; + +static_assert(asl::same_as, uint8_t>); +static_assert(asl::same_as, int64_t>); + diff --git a/asl/base/utility.hpp b/asl/base/utility.hpp index f371ab4..c4801b1 100644 --- a/asl/base/utility.hpp +++ b/asl/base/utility.hpp @@ -69,6 +69,12 @@ constexpr U bit_cast(T value) requires (sizeof(T) == sizeof(U)) return __builtin_bit_cast(U, value); } +template +constexpr auto to_underlying(T value) +{ + return static_cast>(value); +} + // NOLINTBEGIN(*-macro-parentheses) #define ASL_DELETE_COPY(T) \ T(const T&) = delete; \ diff --git a/asl/base/utility_tests.cpp b/asl/base/utility_tests.cpp index 7e54bb2..ea3e7c6 100644 --- a/asl/base/utility_tests.cpp +++ b/asl/base/utility_tests.cpp @@ -81,3 +81,20 @@ ASL_TEST(forward_like) ASL_TEST_EXPECT(test_fwd_like(9) == 4); } +enum class Enum : int // NOLINT +{ + kOne = 1, + kTwo = 2, +}; + +enum Enum2 : int // NOLINT +{ + kOne = 1, + kTwo = 2, +}; + +static_assert(asl::to_underlying(Enum::kOne) == 1); +static_assert(asl::to_underlying(Enum::kTwo) == 2); +static_assert(asl::to_underlying(kOne) == 1); +static_assert(asl::to_underlying(kTwo) == 2); + -- cgit