I have the following function:
template <size_t TSize>
consteval size_t indexOf(SomeEnum someEnum,
const std::array<SomeEnum, TSize> &arr) {
for (size_t i = 0; i < TSize; ++i) {
if (arr[i] == someEnum) {
return i;
}
}
// How to fail here?
return SOME_DEFAULT_WRONG_VALUE;
}
The function should fail instead of returning a default value, but I can't throw an exception or call assert
. I can add a static_assert
to every call to the function (with a macro it will be less horrible), but I'd prefer a solution that works in the function. Is there a way to trigger a compilation failure in such a scenario?
You might simply omit the
return
Demo (clang warns though about that method).
Compiler would reject code reaching that path.
Demo
throw
exception seems cleaner:Demo