5

Assume:

template<class T,int N>
struct A {
  A(): /* here */ {}

  T F[N];
};

I need the elements of F[] to be constructed with {0,1,2,...,N-1}. If possible I would like to avoid recursively defined template structs with defining the last level as template<class T> struct A<T,0> and doing some complicated template tricks. Can C++11 initializer lists help?

This is similar Template array initialization with a list of values, but it does not construct the elements with the increasing value. It sets it later in a run-time loop.

Community
  • 1
  • 1
ritter
  • 7,447
  • 7
  • 51
  • 84

2 Answers2

4

You can do this with a variadic value template and constructor delegation:

template<int... I> struct index {
    template<int n> using append = index<I..., n>; };
template<int N> struct make_index { typedef typename
    make_index<N - 1>::type::template append<N - 1> type; };
template<> struct make_index<0> { typedef index<> type; };
template<int N> using indexer = typename make_index<N>::type;

template<class T, int N>
struct A {
  template<T...I> A(index<I...>): F{I...} {}

  A(): A(indexer<N>{}) {}

  T F[N];
};

This uses the sequence pack generator from Calling a function for each variadic template argument and an array

Community
  • 1
  • 1
ecatmur
  • 152,476
  • 27
  • 293
  • 366
2

Assuming some kind of indices solution is available:

A(): A(make_indices<N>()) {}

// really a private constructor
template<int... Indices>
explicit A(indices<Indices...>)
    // Can be an arbitrary expression or computation, too, like
    // (Indices + 3)...
    : F {{ Indices... }}
{}

If your compiler doesn't support delegating constructors, one option is to switch to std::array<T, N> and use a private static helper that returns an initialized array, such that the default constructor would become:

A(): F(helper(make_indices<N>())) {}

This would of course incur an additional (move) construction.

Community
  • 1
  • 1
Luc Danton
  • 34,649
  • 6
  • 70
  • 114