I'm trying to implement compile-time validation of some hardcoded values. I have the following simplified attempt:
using Type = std::initializer_list<int>;
constexpr bool all_positive(const Type& list)
{
bool all_positive = true;
for (const auto& elem : list)
{
all_positive &= (elem > 0);
}
return all_positive;
}
int main()
{
static constexpr Type num_list{ 1000, 10000, 100 };
static_assert(all_positive(num_list), "all values should be positive");
return 0;
}
gcc compiles this and works exactly as I expected, but clang fails compilation with the error:
static_assert_test.cc:79:16: error: static_assert expression is not an integral constant expression
static_assert(all_positive(num_list), "all values should be positive");
^~~~~~~~~~~~~~~~~~~~~~
static_assert_test.cc:54:20: note: read of temporary is not allowed in a constant expression outside the expression that created the temporary
all_positive &= (elem > 0);
^
static_assert_test.cc:79:16: note: in call to 'all_positive(num_list)'
static_assert(all_positive(num_list), "all values should be positive");
^
static_assert_test.cc:77:32: note: temporary created here
static constexpr Type num_list{ 1000, 10000, 100 };
What's the expected behaviour here? Should this compile or not? And if not, is there an alternative way to validate hard-coded values?