【问题标题】:Initializing a const array with size sizeof(int) [closed]初始化大小为 sizeof(int) 的 const 数组
【发布时间】:2013-11-30 22:56:11
【问题描述】:

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

【问题讨论】:

标签: c++ arrays initialization sizeof


【解决方案1】:

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

【讨论】:

  • 我认为这些是最接近我想要的解决方案。我希望有某种方法可以调用宏递归,但很遗憾得知那是不可能的。
【解决方案2】:

这是初始化 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)};

    ...
}

【讨论】:

  • 谢谢,不过我希望能够在不知道 sizeof(int) 值的情况下对其进行初始化。
  • 如果要求严格基于 sizeof(int),有一些巧妙的方法可以在这个线程上确定 sizeof(int):stackoverflow.com/questions/2584937/…。有了这个,预处理器可以用来确定正确的初始化器。 HTH。
【解决方案3】:

您可以使用 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>();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    • 2014-10-27
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多