1
0
Fork 0
mirror of https://github.com/Neargye/magic_enum.git synced 2026-01-10 23:44:29 +00:00

Introduce contains_value()

* split enum_traits index

* add more proper way to check if enum contains certain value

* change description of contains_value() and add it in readme
This commit is contained in:
oficsu 2020-03-13 12:12:01 +03:00 committed by GitHub
parent 1e6c9a5a5a
commit aa24461613
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 47 additions and 4 deletions

View file

@ -359,20 +359,24 @@ struct enum_traits<E, true> {
return static_cast<U>(value) >= static_cast<U>(reflected_min_v<E>) && static_cast<U>(value) <= static_cast<U>(reflected_max_v<E>);
}
[[nodiscard]] static constexpr int index(E value) noexcept {
if (static_cast<U>(value) >= static_cast<U>(min_v<E>) && static_cast<U>(value) <= static_cast<U>(max_v<E>)) {
[[nodiscard]] static constexpr int index(underlying_type value) noexcept {
if (value >= min_v<E> && value <= max_v<E>) {
if constexpr (is_sparse) {
if (const auto i = indexes[static_cast<U>(value) - min_v<E>]; i != invalid_index_v<E>) {
if (const auto i = indexes[value - min_v<E>]; i != invalid_index_v<E>) {
return i;
}
} else {
return static_cast<U>(value) - min_v<E>;
return value - min_v<E>;
}
}
return -1; // Value out of range.
}
[[nodiscard]] static constexpr int index(E value) noexcept {
return index(static_cast<U>(value));
}
[[nodiscard]] static constexpr E value(std::size_t index) noexcept {
if constexpr (is_sparse) {
return assert(index < count), values[index];
@ -486,6 +490,12 @@ template <typename E>
return std::nullopt; // Value out of range.
}
// Checks whether enum contains enumerator with such value
template <typename E>
[[nodiscard]] constexpr auto contains_value(underlying_type_t<E> value) noexcept -> detail::enable_if_enum_t<E, bool> {
return enum_traits<E>::index(value) != -1;
}
// Returns enum value at specified index.
// No bounds checking is performed: the behavior is undefined if index >= number of enum values.
template <typename E>