c++c++17constexpr

Can't you just make a constexpr array by making a constexpr function that returns an std::array?


I want to construct an array value at compile time and have seen multiple sources online suggesting using a struct with a constexpr constructor:

template<int N>
struct A {
    constexpr A() : arr() {
        for (auto i = 0; i != N; ++i)
            arr[i] = i; 
    }
    int arr[N];
};

int main() {
    constexpr auto a = A<4>();
    for (auto x : a.arr)
        std::cout << x << '\n';
}

Is this just old advice (maybe pre-C++17 advice?) or am I missing something because it seems to me I can just do the following:

constexpr std::array<int, 4> get_ary() {
    std::array<int, 4> ary = {};
    for (int i = 0; i < 4; ++i) {
        ary[i] = i;
    }
    return ary;
}

int main() {
    constexpr auto ary = get_ary();
    static_assert(ary.size() == 4, "The length should be 4!");
}

Solution

  • Can't you just make a constexpr array by making a constexpr function that returns one?

    No, you cannot return an array from a function whether it's constexpr or not.

    You can however return instance of a class that contains an array as a member. Your A is an example of a such class template, and so is std::array. Both examples are allowed.

    The std::array example won't work pre-C++17. There's no issue with returning, but there is an issue with using the non-constexpr operator[].