1

Consider a std::array<T, N> derived class with the following constexpr additions:

static constexpr auto size() { return N; }
constexpr const_reference operator[](size_t Index) const
{
    if (std::is_constant_evaluated())
    {
        static_assert(Index < size(), "Subscript out of range.");
        return data()[Index];
    }
    else
        return std::array<T, N>::operator[](Index);
}

// Outside of class.
constexpr myArray<uint8_t, 42> Array = {};
static_assert(Array[0] == 0, "Never called");

MSVC throws an error on the first static_assert because accessing Index is considered a read of a variable outside its lifetime. Given the nature of the prvalues, I can't figure out why there'd be any lifetime issues for Array[0]. Thoughts?

Convery
  • 183
  • 7
  • `Index` is just a regular old runtime value, I don't understand why you expect to be able to use it in a `static_assert`... (Or maybe you're grossly overestimating the effects of `constexpr`.) – ildjarn Jun 23 '22 at 08:14
  • The simple `return data()[Index];` also uses it and there's no complaints there, and the returned value is used in the last `static_assert` properly. So could you elaborate? – Convery Jun 23 '22 at 08:36
  • Does this answer your question? [Why are 'constexpr' parameters not allowed?](https://stackoverflow.com/questions/27591970/why-are-constexpr-parameters-not-allowed) – AnArrayOfFunctions Jun 23 '22 at 12:40
  • 1
    The problem here is that is a terrible error message. The issue is simply that `Index` isn't a constant expression and needs to be for `static_assert` (because function parameters aren't constexpr). – Barry Jun 23 '22 at 13:19
  • [Related reasoning](https://stackoverflow.com/a/65429926/2069064): `static_assert` takes a _`constant-expression`_, not a constant expression. – Barry Jun 23 '22 at 13:30

0 Answers0