Alex Rivera | Logout

C++: Fill array according to template parameter

Asked 2010-07-01T11:53:36.403
12

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?

Edit
Report

2 Answers

1

You can write a wrapper class, but I'm sure there are cleaner solutions:

template <size_t length>
class array_init_1_to_n
{
    int array[length];

public:

    array_init_1_to_n()
    {
        for (int i = 0; i < length; ++i)
        {
            array[i] = i + 1;
        }
    }

    operator int*()
    {
        return array;
    }

    operator const int*() const
    {
        return array;
    }
};

template<size_t length>
class myClass{
    static array_init_1_to_n<length> array;
};
answered 2010-07-01T12:08:57.490
1

Can't you wrap the array in a static function, so for example,

template<int length>
class myClass {
    static int* myArray() {
        static bool initd = false;
        static int array[length];
        if(!initd) {
            for(int i=0; i<length; ++i) {
                array[i] = i+1;
            }
            initd = true;
        }
        return array;
    };
};

and then access it like,

myClass<4>::myArray()[2] = 42;

It will be initialised on first use, and on following accesses since initd is static, if(!initd) will be false and the initialisation step will be skipped.

answered 2010-07-01T18:42:40.667

Your Answer