If I wanted to initialize an array of constant integers in c++ that has size sizeof(int), how would I go about doing that? For example, I might want an array such that it has sizeof(int)*8 ints with the nth bit on (array[n]=1 << n).
3 Answers
I don't think you can initialize a statically sized array of const objects without specifying each element, at least, not when it isn't a member of class. You can, however, initialize a reference to a statically sized array of const objects:
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();
If you really want to initialize a statically sized array, you can do it using variadic templates but the array would need to be a static member of a class type. Since the code isn't quite as obvious, here it is:
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>
{
};
With that you could then access the array using something like this:
array<>::values[i]
1 Comment
Here's one way to initialize a constant array of 4 integers where 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::bitset, it makes your life easier.