Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ static const array initializer

Tags:

c++

c++11

I have the following class:

const unsigned E = 256;

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

and I want to initialize x as follows:

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

The above assignment seems to be trivial for now. But, the point is to initialize the value of array x based on the index. A quick try seems to tell me that even with c++11 this isn't possible.

Any input?

Thanks.

like image 787
Wen Siang Lin Avatar asked Mar 28 '26 18:03

Wen Siang Lin


1 Answers

If you don't mind storing a std::array instead of a C array, this is pretty simple with an integer sequence:

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>());
}

which you can use as:

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.

like image 72
Casey Avatar answered Apr 01 '26 08:04

Casey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!