c ++ 11:在c ++中创建0到N的constexpr数组 [英] c++11: Create 0 to N constexpr array in c++
本文介绍了c ++ 11:在c ++中创建0到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}
推荐答案
与您对问题的意见中的答案不同,
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
}
这篇关于c ++ 11:在c ++中创建0到N的constexpr数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文