Search code examples
c++c++20consteval

How to fail a consteval function?


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?


Solution

  • You might simply omit the return

    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;
        }
      }
    }
    

    Demo (clang warns though about that method).

    Compiler would reject code reaching that path.

    Demo

    throw exception seems cleaner:

    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;
        }
      }
      throw 42; // or more meaningful exception
    }
    

    Demo