6

Possible Duplicate:
Programmatically create static arrays at compile time in C++

Is it possible to initialize the following array in compile time?

template<int n> void
foo()
{
    static int pairs[2*n]; // = {0,0, 1,1, ..., n-1,n-1}
    for (int i = 0; i < n; i++)
    {
         pairs[2*i] = pairs[2*i+1] = i;
    }

    do_something_with_pairs(pairs);
}

(I use Clang on Xcode 4.5 so C++11 is OK)

Community
  • 1
  • 1
Yoav
  • 5,962
  • 5
  • 39
  • 61

1 Answers1

0

As far as I know it's not possible to extend an array initializer, and that rules out a recursive template based solution as a means to generate static initialization data.

However, you can do the simple thing of having a static array with as many data points as you will ever use. This can be generated by a simple script. Or e.g. by the Boost preprocessor library.

Then you can just use a pointer to that array.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331