Search code examples
c++templatesarraysfill

C++: Fill array according to template parameter


Essentially, the situation is as follows:

I have a class template (using one template parameter length of type int) and want to introduce a static array. This array should be of length length and contain the elements 1 to length.

The code looks as follows up to now:

template<int length>
class myClass{
    static int array[length];
};

Then I wanted to write a line for initalizing the array

// of course, the line below does not work as intended.
template<int length> int myClass<length>::array[length]={1,2, ..., length};

(How) can this be achieved?


Solution

  • Use "static constructor" idiom.

    // EDIT 2

    #include <iostream>
    
    template<int length>
    class myClass {
    public:
        typedef int ArrayType[length];
    
        static struct StaticData {
            ArrayType array;
    
            StaticData()
            {
                for (int i = 0; i < length; i++) array[i] = i;
            }
        }
        static_data;
    
        static ArrayType &array;
    };
    
    template<int length>
    typename myClass<length>::StaticData myClass<length>::static_data;
    
    template<int length>
    typename myClass<length>::ArrayType &myClass<length>::array = myClass<length>::static_data.array;
    
    int main(int argc, char** argv) {
        const int LEN = 5;
        for (int i = 0; i < LEN; i++) {
            std::cout << myClass<LEN>::array[i];
        }
    }