Home > front end >  How to get std array size in a constant expression?
How to get std array size in a constant expression?

Time:04-27

Consider this code:

#include <array>
#include <cstddef>

struct A {
    std::array<std::size_t, 4> test;
    void method() {
        std::size_t duptest[test.size()] = {}; // error: variable-sized object may not be initialized
    }
};

Godbolt Clang

It fails under Clang with the error in the comment. I don't understand why this is considered a VLA, because test.size is a constexpr function. How do I stop duptest from being interpreted as a VLA?

CodePudding user response:

test is not a constant expression so test.size() is not a constant expression, even though std::array::size is constexpr and it's "obviously" always 4. Therefore this is a VLA and is nonstandard.

You might use std::tuple_size.

size_t duptest[std::tuple_size<decltype(test)>()] = {};

CodePudding user response:

The problem is that the expression test.size() is equivalent to this->test.size() but the this object is more of a run-time construct. Therefore this->test.size() cannot be used to specify the size of the array since the size of an array must be a compile time constant(aka constant expression)

  • Related