c++c++11constexprarray-initialization

Create N-element constexpr array in C++11


Hello i'm learning C++11, I'm wondering how to make a constexpr 0 to n array, for example:

n = 5;

int array[] = {0 ... n};

so array may be {0, 1, 2, 3, 4, 5}


Solution

  • In C++14 it can be easily done with a constexpr constructor and a loop:

    #include <iostream>
    
    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';
    }