Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error returning an array from a consteval function

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading