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?