2

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?

2
  • 1
    Have you tried stackoverflow.com/a/42006019/7547712 ? Commented Nov 9, 2021 at 1:27
  • The thing is, for loops aren't the issue. My program has way more complicated constexpr evaluations using for loops that work just fine. It might solve it, but not well. Commented Nov 9, 2021 at 1:33

1 Answer 1

2

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;
    }();
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, that works! Makes sense too. Unhelpful compiler error was pointing to the array instead of the index.
Which compiler are you using? The error message of GCC is relatively clear: error: the value of 'i' is not usable in a constant expression.
I was using Clang. Tried to compile it once in GCC, didn't pay close enough attention. Looking more closely now, Clang does say "read of non-const variable 'i' is not allowed in a constant expression" a few lines down.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.