I use a function like this to convert int
(from a legacy API) to an enum
:
TestEnum to_test_enum(int value) {
TestEnum converted(static_cast<TestEnum>(value));
# pragma GCC diagnostic push
# pragma GCC diagnostic error "-Wswitch"
switch (converted) {
case TestEnum::A:
case TestEnum::B:
return converted;
}
# pragma GCC diagnostic pop
throw std::runtime_error("wrong value");
}
to_test_enum
throws an exception if an invalid value has been passed to to_enum
, otherwise it returns the according TestEnum
value. The pragma
ensures I will get a compiler error in case a legal value is missing.
Lines like these will now convert an integer and do a validity-check at runtime:
enum class TestEnum {
A = 1,
B = 2,
};
auto v1 = to_test_enum(2);
auto v2 = to_test_enum(3); // will throw
Question: I wonder if it's possible with some sort of template magic to turn this into a function template:
template<class E>
E to_enum(int value) {
E converted(static_cast<E>(value));
switch (converted) {
EACH ELEMENT e IN E: case e: <--- here goes some unrolling magic
return converted;
}
throw std::runtime_error("wrong value");
}
The function would then be used like this:
auto v1 = to_enum<TestEnum>(2);
auto v2 = to_enum<TestEnum>(3); // will throw