Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compile-time validation of constexpr std::initializer_list

Tags:

c++

c++14

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?

like image 868
John Ilacqua Avatar asked Feb 08 '18 02:02

John Ilacqua


1 Answers

The problem is that you are trying to use temporary array to initialize your constexpr.

An object of type std::initializer_list is constructed from an initializer list as if the implementation generated and materialized (7.4) a prvalue of type “array of N const E”, where N is the number of elements in the initializer list.

But this temporary array is not a constant per se. It could work like this:

static constexpr array<int,4> arr = { 1000, 10000, 100 };
static constexpr Type num_list(&arr[0], &arr[3]);
static_assert(all_positive(num_list), "all values should be positive");
like image 127
Yola Avatar answered Sep 21 '22 12:09

Yola