From 7237e3ac3f8752aac71182ee2b80ffecbe1328fa Mon Sep 17 00:00:00 2001 From: Vitaly Fanaskov Date: Mon, 6 Nov 2023 10:57:55 +0100 Subject: [PATCH] Explicitly mark the result of detail::names as constexpr It might make no sense, but on MSVC it can generate a compile-time error, especially if an enumerator's value is out of range. Example: error C3615: constexpr function 'magic_enum::detail::names' cannot result in a constant expression ... note: failure was caused by call of undefined function or one not declared 'constexpr' ... note: see usage of '__builtin_array_init_helper' --- include/magic_enum.hpp | 3 ++- test/test.cpp | 12 ++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/include/magic_enum.hpp b/include/magic_enum.hpp index 53e01c0a1..5ff41061a 100644 --- a/include/magic_enum.hpp +++ b/include/magic_enum.hpp @@ -827,7 +827,8 @@ inline constexpr auto max_v = (count_v > 0) ? static_cast(values_v constexpr auto names(std::index_sequence) noexcept { - return std::array{{enum_name_v[I]>...}}; + constexpr auto result = std::array{{enum_name_v[I]>...}}; + return result; } template diff --git a/test/test.cpp b/test/test.cpp index f974de247..3e46e044d 100644 --- a/test/test.cpp +++ b/test/test.cpp @@ -510,6 +510,11 @@ class a_foo2 { }; } // namespace +enum class LargeNumbers { + First = -1024, + Second = 1024 +}; + TEST_CASE("enum_name") { SECTION("automatic storage") { constexpr Color cr = Color::RED; @@ -646,6 +651,13 @@ TEST_CASE("enum_name") { REQUIRE(enum_name() == "ONE"); REQUIRE(enum_name() == "ONE"); } + + SECTION("empty if the value is out of range") { + const auto ln_value = GENERATE(LargeNumbers::First, LargeNumbers::Second); + const auto ln_name = enum_name(ln_value); + + REQUIRE(ln_name.empty()); + } } TEST_CASE("enum_names") {