I’m trying to create a constant function that takes in a size int as a template parameter and returns an array that size with each index filled with its respective power of 2.
template <int sz>
consteval int* conflagtab() {
int ar[sz] = {};
for (unsigned int i = 0; i < sz - 1; i++) {
ar[i] = conflag(i);
}
return ar;
}
However when I am trying to use it I get the error:
call to consteval function “conflagtab<sz>() [with sz=31]” did not
produce a valid constant expression.
I tried putting it in global namespace to see if that had a change but it had no difference. I’m expecting it to just return a pointer to the array.
6
You can’t return a raw array from a consteval
function, especially by pointer. Your example, if it were not consteval
, would be a dangling pointer. Returning something that new[]
created is not permitted in consteval
You can return a std::array
:
template <int sz>
consteval std::array<int, sz> conflagtab() {
std::array<int, sz> ar;
for (unsigned int i = 0; i < sz - 1; i++) {
ar[i] = conflag(i);
}
return ar;
}