mirror of
https://github.com/Neargye/magic_enum.git
synced 2026-01-09 23:34:23 +00:00
add integer_cast
This commit is contained in:
parent
4a540b1a2e
commit
0c1128947b
2 changed files with 37 additions and 0 deletions
|
|
@ -55,6 +55,18 @@ int main() {
|
|||
std::cout << "GREEN = " << c3.value() << std::endl; // GREEN = 10
|
||||
}
|
||||
|
||||
// Enum value to integer value.
|
||||
auto color_underlying = magic_enum::integer_cast(Color::RED);
|
||||
if (color_underlying.has_value() && color_underlying.value() == static_cast<std::underlying_type_t<Color>>(Color::RED)) {
|
||||
std::cout << "RED = " << color_underlying.value() << std::endl; // RED = -10
|
||||
}
|
||||
|
||||
// Enum value to specific type integer value.
|
||||
auto color_int = magic_enum::integer_cast<int>(Color::RED);
|
||||
if (color_int.has_value() && color_int.value() == static_cast<int>(Color::RED)) {
|
||||
std::cout << "RED = " << color_int.value() << std::endl; // RED = -10
|
||||
}
|
||||
|
||||
using namespace magic_enum::ops; // out-of-the-box stream operator for enums.
|
||||
// ostream operator for enum.
|
||||
std::cout << "Color: " << c1 << " " << c2 << " " << c3 << std::endl; // Color: RED BLUE GREEN
|
||||
|
|
|
|||
|
|
@ -242,6 +242,31 @@ template <typename E, typename = detail::enable_if_enum_t<E>>
|
|||
}
|
||||
}
|
||||
|
||||
// Obtains integer value from enum value.
|
||||
template <typename E, typename D = std::decay_t<E>, typename = detail::enable_if_enum_t<D>>
|
||||
[[nodiscard]] constexpr std::optional<std::underlying_type_t<D>> integer_cast(E value) noexcept {
|
||||
static_assert(std::is_enum_v<D>, "magic_enum::integer_cast requires enum type.");
|
||||
|
||||
if (detail::name_impl<D>(static_cast<int>(value)).empty()) {
|
||||
return std::nullopt; // Invalid value or out of range.
|
||||
} else {
|
||||
return static_cast<std::underlying_type_t<D>>(value);
|
||||
}
|
||||
}
|
||||
|
||||
// Obtains specific type integer value from enum value.
|
||||
template <typename I, typename E, typename D = std::decay_t<E>, typename = std::enable_if_t<std::is_enum_v<D> && std::is_arithmetic_v<I>>>
|
||||
[[nodiscard]] constexpr std::optional<I> integer_cast(E value) noexcept {
|
||||
static_assert(std::is_enum_v<D>, "magic_enum::integer_cast requires enum type.");
|
||||
static_assert(std::is_arithmetic_v<I>, "magic_enum::integer_cast requires integer type.");
|
||||
|
||||
if (detail::name_impl<D>(static_cast<int>(value)).empty() || static_cast<I>(value) != static_cast<std::underlying_type_t<D>>(value)) {
|
||||
return std::nullopt; // Invalid value or out of range.
|
||||
} else {
|
||||
return static_cast<I>(value);
|
||||
}
|
||||
}
|
||||
|
||||
// Returns enum value at specified index.
|
||||
// No bounds checking is performed: the behavior is undefined if index >= number of enum values.
|
||||
template<typename E, typename = detail::enable_if_enum_t<E>>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue