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?
CodePudding user response:
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;
}();
}