Neargye / magic_enum

Static reflection for enums (to string, from string, iteration) for modern C++, work with any enum type without any macro or boilerplate code
MIT License
4.99k stars 445 forks source link

enum_values does not work with the following enum #246

Closed sc-ele closed 1 year ago

sc-ele commented 1 year ago

enum E { X = 1, Y = 2, Z = X | Y };

enum_values misses Z!

Can it be done?

Neargye commented 1 year ago

Hi,

For enum-flags add is_flags to specialization enum_range for necessary enum type. Specialization of enum_range must be injected in namespace magic_enum::customize.

enum class Directions { Up = 1 << 1, Down = 1 << 2, Right = 1 << 3, Left = 1 << 4 };
template <>
struct magic_enum::customize::enum_range<Directions> {
  static constexpr bool is_flags = true;
};

If not add is_flags then the default range for magic_enum is -128 to 128 see https://github.com/Neargye/magic_enum/blob/master/doc/limitations.md. Also you can force control "flags-behavior", for example

magic_enum::enum<as_common<>>(E::Z) -> 'Z'
magic_enum::enum<as_flags<>>(E::Z) -> '' // null-string

Zero is not flag, aslo are "bits or" Z = X | Y is not flag. Unfortunately, these libs restrictions.