From 36ab9fa1a43a43615539e0302fa3f75988a34d68 Mon Sep 17 00:00:00 2001 From: bjacklyn Date: Sun, 10 Jan 2021 04:43:47 -0800 Subject: [PATCH] Detect values out of range and fail compilation (#70) This checks for a value at (range_min - 1) and (range_max + 1) for numerical enums (i.e. not flag enums) and fails compilation with a static_assert if any value is found Co-authored-by: Brandon Jacklyn --- include/magic_enum.hpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/include/magic_enum.hpp b/include/magic_enum.hpp index 5a5f4b2..955aec2 100644 --- a/include/magic_enum.hpp +++ b/include/magic_enum.hpp @@ -434,12 +434,31 @@ constexpr auto values(std::index_sequence) noexcept { return values; } +template > +inline static constexpr void detect_values_out_of_range() +{ + constexpr auto min = reflected_min_v; + constexpr auto max = reflected_max_v; + constexpr auto range_size = max - min + 1; + + if constexpr (cmp_less((std::numeric_limits::min)(), min) && !IsFlags) + { + static_assert(!is_valid(0)>(), "magic_enum detects enum value smaller than min range size"); + } + + if constexpr (cmp_less(range_size, (std::numeric_limits::max)()) && !IsFlags) + { + static_assert(!is_valid(range_size + 1)>(), "magic_enum detects enum value larger than max range size"); + } +} + template > constexpr auto values() noexcept { static_assert(is_enum_v, "magic_enum::detail::values requires enum type."); constexpr auto range_size = reflected_max_v - reflected_min_v + 1; static_assert(range_size > 0, "magic_enum::enum_range requires valid size."); static_assert(range_size < (std::numeric_limits::max)(), "magic_enum::enum_range requires valid size."); + detect_values_out_of_range(); return values>(std::make_index_sequence{}); }