在C ++ 11中创建N元素constexpr数组

问题描述:

你好,我正在学习C ++ 11,我想知道如何使constexpr 0到n数组,例如:

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};

所以数组可能是 {0,1,2,3,4, 5}

在C ++ 14中,使用 constexpr 构造函数和一个循环:

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';
}