正在初始化大小为(int)的常量数组

Initializing a const array with size sizeof(int)

本文关键字:常量 数组 int 初始化 小为      更新时间:2023-10-16

如果我想在c++中初始化一个大小为(int)的常量整数数组,我该怎么做?例如,我可能想要一个数组,它的大小为(int)*8 int,第n位为(array[n]=1<<n)。

我不认为在不指定每个元素的情况下初始化静态大小的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]

这里有一种初始化4个整数的常量数组的方法,其中sizeof(int)==4:

#define SHIFT(__n) (1 << __n++)
int main()
{
    int n = 0;
    const int ir4[sizeof(int)] = {SHIFT(n), SHIFT(n), SHIFT(n), SHIFT(n)};
    ...
}

您可以使用std::array和模板

template<typename T, std::size_t N>
std::array<T, sizeof(T)*N> array_init() {
    std::array<T, sizeof(T)*N> ints;
    for (T n = 0; n < sizeof(T)*N; ++n) {
    ints[n] = 1 << n;
    }
    return ints;
}

然后你把它叫做

auto ints = array_init<int, 8>();