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

Difficulties getting a constexpr property from a constexpr array

I’m having this issue where I can’t seem to, at compile time, check if all elements in an std::array are equal. It seems so simple and I’m not new to C++ by any means, but I can’t figure it out! (I would just use <algorithm> but sadly those aren’t marked constexpr in C++17, and I’m stuck with C++17 because CUDA.)

Here’s an example (that doesn’t compile).

#include <array>

int main()
{
    constexpr std::array<int, 3> a {0, 0, 0};

    constexpr bool equal = [=](){
        for (int i = 1; i < 3; i++)
        {   
            if constexpr (a[0] != a[i])
                return false;
        }
        return true;
    }();
}

Why does a[0] != a[i] not qualify as constexpr? (This is the error GCC and Clang give me.) How do I get the result I need?

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

>Solution :

Since your i is not a compile-time constant, you cannot use if constexpr. A simple if is enough which still can check your array at compile-time.

#include <array>

int main()
{
    constexpr std::array<int, 3> a {0, 0, 0};

    constexpr bool equal = [=](){
        for (int i = 1; i < 3; i++)
        {   
            if (a[0] != a[i])
          //^^
                return false;
        }
        return true;
    }();
}
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