I'm trying to initialize a constexpr
array using C++17
via the following:
template <size_t N>
struct CStr
{
static constexpr std::array<int, N> getArr()
{
std::array<int, N> a;
for (auto idx = 0; idx < a.size(); ++idx)
{
a[idx] = idx * idx;
}
return a;
}
static constexpr auto arr { getArr()};
};
int main()
{
for (const auto &el : CStr<10>::arr)
{
std::cout << el << std::endl;
}
}
However this results in the following compile error about getArr
not being a constexpr
function. Can someone help explain why ?
<source>: In instantiation of 'constexpr const std::array<int, 10> CStr<10>::arr':
<source>:18:27: required from 'struct CStr<10>'
<source>:24:35: required from here
<source>:18:39: error: 'static constexpr std::array<int, N> CStr<N>::getArr() [with long unsigned int N = 10]' called in a constant expression
18 | static constexpr auto arr { getArr()};
| ~~~~~~^~
<source>:9:41: note: 'static constexpr std::array<int, N> CStr<N>::getArr() [with long unsigned int N = 10]' is not usable as a 'constexpr' function because:
9 | static constexpr std::array<int, N> getArr()
| ^~~~~~
<source>:12:9: error: 'goto' is not a constant expression
12 | for (auto idx = 0; idx < a.size(); ++idx)
| ^~~
Compiler returned: 1 | ^~~~~