0

I'm writing an EnumSet class for a project. I would like to have an EnumSet::AllOf() method if possible, like in Java. The obvious way to go about this is to iterate over every member of the std::underlying_type and try casting it to the enum class, then go from the first element where this is possible to the last.

You are not given what the lowest or highest element of the enum is, so you must search the entire space.

Is this even possible? If so, how?

EDIT FOR CLARITY: I'm looking for something along the lines of

try {
    std::dynamic_cast<std::underlying_type<E>::type>(e);
    return true; // Cast succeeded, enum is valid
} catch (SOME_KIND_OF_EXCEPTION e) {
    return false; // Cast failed, enum is invalid
}
Q Science
  • 111
  • 7
  • 1
    C++ does not provide those kinds of facilities. It is possible (for some definition of "possible"), but only insofar as the programmer makes functions that do those things, for every enum for which one wants to do those things. – Eljay Mar 17 '19 at 20:08
  • No, it is impossible. – HolyBlackCat Mar 17 '19 at 20:54
  • "*The obvious way to go about this is to iterate over every member of the std::underlying_type*" I don't know what that means. The underlying type of an enumeration is an integer of some form; it doesn't have members. – Nicol Bolas Mar 17 '19 at 21:17
  • @NicolBolas `for (int i = MIN_VALUE; i <= MAX_VALUE; i++) { if (canBeCastedToEnum(i)) { // do stuff } }` where MIN_VALUE and MAX_VALUE depend on the size and signedness of the underlying type – Q Science Mar 17 '19 at 21:58
  • @QScience: There *is no* `canBeCastedToEnum` function in C++. So even if that loop were not over 2^31 integer values, there's no way to know which ones are valid enumerators. – Nicol Bolas Mar 18 '19 at 02:00
  • @q-science try https://github.com/Neargye/magic_enum. You can check valid int value by enum_cast, or get all values by enum_values. – Neargye Jul 23 '19 at 13:47

0 Answers0