Skip to content

Commit

Permalink
Explicitly mark the result of detail::names as constexpr
Browse files Browse the repository at this point in the history
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'
  • Loading branch information
vt4a2h committed Nov 6, 2023
1 parent 49bb72d commit 7237e3a
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
3 changes: 2 additions & 1 deletion include/magic_enum.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -827,7 +827,8 @@ inline constexpr auto max_v = (count_v<E, S> > 0) ? static_cast<U>(values_v<E, S

template <typename E, enum_subtype S, std::size_t... I>
constexpr auto names(std::index_sequence<I...>) noexcept {
return std::array<string_view, sizeof...(I)>{{enum_name_v<E, values_v<E, S>[I]>...}};
constexpr auto result = std::array<string_view, sizeof...(I)>{{enum_name_v<E, values_v<E, S>[I]>...}};
return result;
}

template <typename E, enum_subtype S>
Expand Down
12 changes: 12 additions & 0 deletions test/test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -646,6 +651,13 @@ TEST_CASE("enum_name") {
REQUIRE(enum_name<Binary::ONE>() == "ONE");
REQUIRE(enum_name<MaxUsedAsInvalid::ONE>() == "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") {
Expand Down

0 comments on commit 7237e3a

Please sign in to comment.