Create N-element constexpr array in C++11

2019-01-03 02:29发布

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}

7条回答
Viruses.
2楼-- · 2019-01-03 03:19

Unlike those answers in the comments to your question, you can do this without compiler extensions.

#include <iostream>

template<int N, int... Rest>
struct Array_impl {
    static constexpr auto& value = Array_impl<N - 1, N, Rest...>::value;
};

template<int... Rest>
struct Array_impl<0, Rest...> {
    static constexpr int value[] = { 0, Rest... };
};

template<int... Rest>
constexpr int Array_impl<0, Rest...>::value[];

template<int N>
struct Array {
    static_assert(N >= 0, "N must be at least 0");

    static constexpr auto& value = Array_impl<N>::value;

    Array() = delete;
    Array(const Array&) = delete;
    Array(Array&&) = delete;
};

int main() {
    std::cout << Array<4>::value[3]; // prints 3
}
查看更多
登录 后发表回答