我认为你不能在不指定每个元素的情况下初始化一个静态大小的const 对象数组,至少在它不是类成员的情况下是这样。但是,您可以初始化对 const 对象的静态大小数组的引用:
template <int N>
struct foo
{
static bool init(int* array) {
unsigned int bit(1);
for (int i(0); i != N; ++i) {
array[i] = bit << i;
}
return true;
}
static void use(bool) {}
static int const (&array())[N] {
static int rc[N];
static bool dummy(init(rc));
use(dummy);
return rc;
}
};
int const (&array)[sizeof(int) * 8] = foo<sizeof(int) * 8>::array();
如果您真的想初始化一个静态大小的数组,您可以使用可变参数模板来完成,但该数组需要是类类型的静态成员。由于代码不是很明显,这里是:
template <int...> struct indices {};
template <int N, typename> struct make_list;
template <int... Indices>
struct make_list<0, indices<Indices...>> {
typedef indices<0, Indices...> type;
};
template <int N, int... Indices>
struct make_list<N, indices<Indices...>> {
typedef typename make_list<N-1, indices<N, Indices...>>::type type;
};
template <int N, typename> struct array_aux;
template <int N, int... Indices>
struct array_aux<N, indices<Indices...>>
{
static int const values[N];
};
template <int N, int... Indices>
int const array_aux<N, indices<Indices...>>::values[N] = { 1u << Indices... };
template <int N = sizeof(int) * 8>
struct array
: array_aux<N, typename make_list<N-1, indices<>>::type>
{
};
这样您就可以使用以下方式访问数组:
array<>::values[i]