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?

Chris
  • 26,361
  • 5
  • 21
  • 42

1 Answers1

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;
    }();
}
康桓瑋
  • 33,481
  • 5
  • 40
  • 90
  • Thanks, that works! Makes sense too. Unhelpful compiler error was pointing to the array instead of the index. – Olaf Willocx Nov 09 '21 at 01:34
  • Which compiler are you using? The error message of GCC is [relatively clear](https://godbolt.org/z/Mq51fasvq): `error: the value of 'i' is not usable in a constant expression`. – 康桓瑋 Nov 09 '21 at 01:41
  • 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. – Olaf Willocx Nov 09 '21 at 01:49