How to fail a consteval function?

4

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?

Share
Improve this question
16
  • 2
    Generally these kinds of functions don't fail if they can't find the data, they return an out of bounds marker (usually -1). It's perfectly valid to search for something that doesn't exist in your collection. – Blindy 15 hours ago
  • 2
    Why can't you throw an exception or use assert? – chris 15 hours ago
  • 1
    You can still throw from a constexpr. I'm not familiar enough with consteval to be certain, but I believe you should be able to throw from them as well. – François Andrieux 15 hours ago
  • 1
    Can you please clarify whether you think throwing is not allowed in consteval or if you have an external requirement that you not use throw? – François Andrieux 15 hours ago
  • 1
    @chris: It can. One of the answers mentions this. – Nicol Bolas 15 hours ago

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

flutter websocket connection issue