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)

3
  • the loop uses indices beyond the end of the array => Undefined Behavior. Commented Nov 29, 2012 at 11:42
  • Sorry, I fixed that now. Commented Nov 29, 2012 at 11:44
  • 2
    I'm wondering how many people have put their work aside and trying hard to solve this. This is a very good question. But I'm giving up. Commented Nov 29, 2012 at 11:50

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.