0

The standard says that the expression in a static_assert should be a constant expression of type bool. Does that somehow not cover expressions including function parameters known at compile time? The following, for example:

#include <array>
#include <iostream>

constexpr std::array names = {"foo", "bar"};

constexpr const char* name(std::size_t i) noexcept {
    static_assert(i < names.size(), "");
    return names[i];
}

// Type your code here, or load an example.
int main() {
    std::cout << name(0) << std::endl;
}

fails with

<source>: In function 'constexpr const char* name(std::size_t)':
<source>:7:21: error: non-constant condition for static assertion
    7 |     static_assert(i < names.size(), "");
      |                   ~~^~~~~~~~~~~~~~
<source>:7:21: error: 'i' is not a constant expression

which I find surprising since the compiler should clearly see that i is 0.

Is it possible to make this work?

Brian61354270
  • 8,690
  • 4
  • 21
  • 43
giik
  • 117
  • 6
  • 2
    A `constexpr` function means that if the input parameter is a constant expression, the output is a constant expression as well. It doesn't actually require the input argument to be a constant expression, and inside the body of it the local variable is not `constexpr`. So `i` isn't a constant expression. You might want to template the function over `i`, or in C++20 make it `consteval`. – Nathan Pierson Aug 20 '21 at 15:09
  • 1
    (Actually I don't think `consteval` will do anything about function arguments not being constant expressions within the body of a function, I think making it a non-type template parameter is the only way to use it in a static assertion. See [here](https://stackoverflow.com/questions/56130792/will-consteval-functions-allow-template-parameters-dependent-on-function-argumen).) – Nathan Pierson Aug 20 '21 at 15:34
  • Thanks, and yeah, that seems to be the case (making the parameter a non-type template parameter works). – giik Aug 21 '21 at 21:00

0 Answers0