From 3b2ebf7e553d6ae4969281d506d9045acb1eafb7 Mon Sep 17 00:00:00 2001 From: neargye Date: Mon, 18 Nov 2019 13:35:59 +0500 Subject: [PATCH] add enum concept --- example/example.cpp | 10 ++++++++-- include/magic_enum.hpp | 12 ++++++++++-- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/example/example.cpp b/example/example.cpp index 16b651f..09ec163 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -26,6 +26,12 @@ enum class Color : int { RED = -10, BLUE = 0, GREEN = 10 }; +template +auto to_integer(magic_enum::Enum value) { + // magic_enum::Enum - C++17 Concept for enum type. + return static_cast>(value); +} + int main() { // Enum variable to string name. Color c1 = Color::RED; @@ -44,7 +50,7 @@ int main() { // String name to enum value. auto c2 = magic_enum::enum_cast("BLUE"); if (c2.has_value() && c2.value() == Color::BLUE) { - std::cout << "BLUE = " << static_cast(c2.value()) << std::endl; // BLUE = 0 + std::cout << "BLUE = " << to_integer(c2.value()) << std::endl; // BLUE = 0 } // Integer value to enum value. @@ -55,7 +61,7 @@ int main() { // Enum value to integer value. auto color_integer = magic_enum::enum_integer(Color::RED); - if (color_integer == static_cast>(Color::RED)) { + if (color_integer == to_integer(Color::RED)) { std::cout << "RED = " << color_integer << std::endl; // RED = -10 } diff --git a/include/magic_enum.hpp b/include/magic_enum.hpp index a2d7bdf..c762bd1 100644 --- a/include/magic_enum.hpp +++ b/include/magic_enum.hpp @@ -97,7 +97,9 @@ inline constexpr bool is_enum_v = std::is_enum_v && std::is_same_v struct static_string { - constexpr static_string(std::string_view str) noexcept : static_string{str, std::make_index_sequence{}} {} + constexpr static_string(std::string_view str) noexcept : static_string{str, std::make_index_sequence{}} { + assert(str.size() == N); + } constexpr const char* data() const noexcept { return chars.data(); } @@ -109,7 +111,7 @@ struct static_string { template constexpr static_string(std::string_view str, std::index_sequence) noexcept : chars{{str[I]...}} {} - const std::array chars; + const std::array chars; }; template <> @@ -308,6 +310,9 @@ constexpr auto entries(std::index_sequence) noexcept { template using enable_if_enum_t = std::enable_if_t>, R>; +template >>> +using enum_concept = T; + template > struct is_scoped_enum : std::false_type {}; @@ -392,6 +397,9 @@ struct enum_traits>> { // Checks is magic_enum supported compiler. inline constexpr bool is_magic_enum_supported = detail::supported::value; +template +using Enum = detail::enum_concept; + // Checks whether T is an Unscoped enumeration type. // Provides the member constant value which is equal to true, if T is an [Unscoped enumeration](https://en.cppreference.com/w/cpp/language/enum#Unscoped_enumeration) type. Otherwise, value is equal to false. template