C++静态常量数组初始化器

3

我有以下的类:

const unsigned E = 256;

class A {
    public:
        static const unsigned x[E];
    ...
}

我希望初始化x变量的方法如下:

const unsigned A::x[E] = { 1, 2, 3, ..., E };

目前看来,上述分配似乎微不足道。但是,关键在于根据索引初始化数组x的值。快速尝试告诉我即使使用c++11也不可能实现。

有任何建议吗?

谢谢。


它在技术上并不算初始化,但std::iota可能适合你的需求... - ildjarn
数组到底有什么用处呢? - Avidan Borisov
听起来像是 std::integer_sequence,但它直到 C++14 才可用。http://en.cppreference.com/w/cpp/utility/integer_sequence - imreal
顺序初始化是第一个使用案例。它可能会变得更加复杂,例如:{ f(0), f(1), f(2), ... }。 - Wen Siang Lin
2个回答

2

如果您不介意存储std::array而不是C数组,那么使用整数序列就非常简单:

template <int...I>
struct indices {};
template <int N, int...I>
struct make_indices : make_indices<N-1, N-1, I...> {};
template <int...I>
struct make_indices<0, I...> : indices<I...> {};

template <typename T, int...I>
constexpr std::array<T, sizeof...(I)>
iota_array_helper(indices<I...>) {
  return {I...};
}

template <typename T, std::size_t N>
constexpr std::array<T, N>
iota_array() {
  return iota_array_helper<T>(make_indices<N>());
}

您可以将其用作:
const unsigned E = 256;

class A {
    public:
        static const std::array<unsigned, E> x;
    ...
};

std::array<unsigned, E> A::x = iota_array<unsigned, E>();

Here it is live.


这个可以工作,但仍需要一些修改,因为我希望数组是A :: x [0] = 1,[1] = 2等。这种级别的模板超出了我的能力范围。有哪些好的参考资料可以阅读? - Wen Siang Lin
@WenSiangLin:FYI,唯一需要修改的是将整数偏移量改为A::x[0]=1, [1]=2,只需将return {I...};更改为return {(I+1)...};即可。这可以通过向iota_arrayiota_array_helper添加一个额外的非类型模板参数来进行泛化以保存偏移量。 - ildjarn

0

你可以使用一些递归技巧

template<int... values>
struct myclass {
    static const unsigned char x[sizeof...(values)];
};

template<int... values>
const unsigned char myclass<values...>::x[sizeof...(values)] = { values... };

template<int count, int... values>
struct iota_array {
    typedef typename iota_array<count-1, count-1, values...>::value value;
};

template<int... values>
struct iota_array<0, values...> {
    typedef myclass<values...> value;
};

typename iota_array<E>::value myinstance;

当然你可以这样做,但这并不意味着你应该这样做。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接